简体   繁体   English

使用 conda 在 cron 上运行 python 脚本

[英]Run python script on cron using conda

Trying to send some output to Slack using cron on an instance of GCP Compute Engine running Linux Ubuntu 18.04.2 LTS .尝试在运行 Linux Ubuntu 18.04.2 LTS的 GCP Compute Engine 实例上使用 cron 将一些输出发送到 Slack。

Output is generated by python script.输出由 python 脚本生成。

Python script is usually run using conda activate my_env and python my_script.py Python 脚本通常使用conda activate my_envpython my_script.py

I have made the bash file executable by doing chmod +x my_script.bash我通过执行chmod +x my_script.bash使 bash 文件可执行

Here is content of bash file:这是 bash 文件的内容:

#!/bin/bash
source /home/user/miniconda3/bin/activate
conda activate my_env
python /home/user/folder/cron/reports.py -r check_stocks

I would expect adding the following line to crontab -e :我希望将以下行添加到crontab -e

00 21 * * * cd /home/user/folder/cron/ && /bin/bash my_script.bash would give me the same results. 00 21 * * * cd /home/user/folder/cron/ && /bin/bash my_script.bash会给我相同的结果。

I run cd /home/user/folder/cron/ && /bin/bash my_script.bash in my shell and the script runs fine.我在我的 shell 中运行cd /home/user/folder/cron/ && /bin/bash my_script.bash并且脚本运行良好。

Make your .py file exacutable too ( chmod +x file.py ) - otherwise it won't work.使您的 .py 文件也可以执行( chmod +x file.py ) - 否则它将无法工作。 You can find similar issue resolved here .您可以在此处找到已解决的类似问题。

I had a similar issue and I gave up activating the conda environment and instead called directly the python bin in the miniconda environment folder, like this:我有一个类似的问题,我放弃了激活conda环境,而是直接调用 miniconda 环境文件夹中的 python bin,如下所示:

00 21 * * * /home/myuser/miniconda3/envs/my_env/bin/python /home/user/folder/cron/reports.py

I don't think this is the recommended solution, especially if you have a complex project with dependencies and you are importing a lot of modules, but for my simple script it solved the problem.我不认为这是推荐的解决方案,特别是如果您有一个具有依赖项的复杂项目并且您要导入很多模块,但是对于我的简单脚本,它解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM