[英]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.我目前正在努力解决如何通过 crontab 在虚拟环境中从 python 文件运行方法。
I have a directory that looks as follows: /home/ubuntu/project
has the file file.py
and the folder venv
in it.我有一个如下所示的目录:
/home/ubuntu/project
中有文件file.py
和文件夹venv
。 In file.py
there is a method()
that I want to execute regularly via crontab, using the python and dependencies of the virtual environment.在
file.py
中有一个method()
,我想通过 crontab 定期执行,使用 python 和虚拟环境的依赖项。
I have already figured out that I need to use the python from inside the virtual environment, so instead of我已经发现我需要在虚拟环境中使用 python ,所以而不是
python3
I use我用
/home/ubuntu/project/venv/bin/python3
. /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()'
python3 -c 'import foo; print foo.hello()'
. 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.非常感谢您考虑这个问题。
The argument to import
is not a file name. import
的参数不是文件名。 The simplest workaround is probably to cd
into the directory, then run the script with the virtual environment's Python interpreter.最简单的解决方法可能是
cd
进入目录,然后使用虚拟环境的 Python 解释器运行脚本。
42 17 * * * cd project && ./venv/bin/python3 -c 'import file; file.method()'
from the crontab
of the user whose home directory is /home/ubuntu
.来自主目录为
/home/ubuntu
的用户的crontab
。
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.更一般地说,您要从中导入的目录需要在您的
PYTHONPATH
上,因此您可以等效地将其设置为目录而不是cd
。 A third alternative is to make the code in file.py
into an installable module, and install it in the virtual environment.第三种选择是将
file.py
中的代码制作成可安装的模块,并将其安装在虚拟环境中。 For a one-off, this may be an unnecessary chore, but it is definitely the most robust and sustainable solution.对于一次性的,这可能是不必要的苦差事,但它绝对是最强大和可持续的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.