Search code examples
pythonpython-3.xcronvirtualenvubuntu-20.04

Run python method in virtualenv from crontab


I am currently struggling with how to run a method from a python file in a virtual environment via crontab.

I have a directory that looks as follows: /home/ubuntu/project has the file file.py and the folder venv in it. In file.py there is a method() that I want to execute regularly via crontab, using the python and dependencies of the virtual environment.

I have already figured out that I need to use the python from inside the virtual environment, so instead of

python3

I use

/home/ubuntu/project/venv/bin/python3.

Now, I have also found answers to the question how to run a method from the command line, namely via

python3 -c 'import foo; print foo.hello()'.

I have tried to combine the two, but unfortunately

/home/ubuntu/project/venv/bin/python3 -c 'import /home/ubuntu/project/file; print(file.method())'

is invalid syntax. Also

/home/ubuntu/project/venv/bin/python3 -c 'from /home/ubuntu/project/ import file; print(file.method())'

only results in errors. On the other hand,

/home/ubuntu/project/venv/bin/python3 -c 'import file; print(file.method())'

results in file not being found.

How do I do this properly?

Thank you very much for considering this question.


Solution

  • The argument to import is not a file name. The simplest workaround is probably to cd into the directory, then run the script with the virtual environment's Python interpreter.

    42 17 * * * cd project && ./venv/bin/python3 -c 'import file; file.method()'
    

    from the crontab of the user whose home directory is /home/ubuntu.

    More generally, the directory you want to import from needs to be on your PYTHONPATH,so you could equivalently set that instead of cd into the directory. A third alternative is to make the code in file.py into an installable module, and install it in the virtual environment. For a one-off, this may be an unnecessary chore, but it is definitely the most robust and sustainable solution.