3
  • I have users root and user1
  • All of my python scripts have been created by user1
  • I have created a bash file that needs to be automated. The bash file calls my python scripts
  • I have added my bash call to the cron file

However, my python environment for root is not the same as it is for user1 (different versions, library packages, etc, etc). So when the cron kicks off, it gives me python errors like "library not found" because the root environment is being used.

How can I ensure that my cron commands run my python scripts under the user1 python environment and not root?

Note that I've already tried using some variation of su in my cron file but it always asks for a password and I need this to be a fully automated process.

1
  • Use python virtual environments and then specify the full path to the python binary within the virtual environment.
    – jordanm
    Jul 27, 2018 at 15:11

2 Answers 2

3

Have you tried using sudo su?

sudo su -l "user1" -c "/path/to/bashscript.sh"

Alternatively you could set the required environment at the top of your crontab:

SHELL=/usr/local/bin/bash
PATH=<user1 path>
LOGNAME=user1
USER=user1
HOME=/home/user1

And if necessary source your user1 config file(s) prior to executing your bash file:

0 12 * * * * . /home/user1/.bash_profile; /path/to/bashscript.sh
1
  • 1
    The very first line in your answer worked for me, exactly what I need to do. Thank you! Jul 27, 2018 at 15:37
-1

If you are using virtual environments, you can also activate the environment in cron:

0 12 * * * * . /%user1-venv-location%/bin/activate; /path/to/bashscript.sh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .