简体   繁体   English

如果脚本不在主文件夹中,则Cron无法运行Python脚本

[英]Cron not running Python script if script not in home folder

I know cron is capricious and I am trying to figure out how to deal with it on linux. 我知道cron反复无常,我正在尝试弄清楚如何在linux上处理它。

I have the following test_cron.py executable Python script for testing cron : 我有以下用于测试cron的test_cron.py可执行Python脚本:

#!/usr/bin/env python

import os

os.makedirs('test_cron_dir')
f = open('test_cron_dir/test_file','w')
f.write('stuff')
f.close()

I added two lines to my crontab to run the script in two different folders : 我在crontab中添加了两行以在两个不同的文件夹中运行脚本:

* * * * * python /home/me/test_cron.py
* * * * * python /home/me/some_folder/test_cron.py

The problem is : cron runs the test_cron.py script located in /home/me/ but does not run the one located in /home/me/some_folder/ . 问题是:cron的运行test_cron.py位于脚本/home/me/但不运行在一个位于/home/me/some_folder/ I have changed the paths in the script to absolute paths but it does not change anything to the situation. 我已经将脚本中的路径更改为绝对路径,但是它并没有改变任何情况。 Also, I have tried to use the root crontab and it does not change anything. 另外,我尝试使用根crontab,它不会改变任何内容。

Can anyone please shine the light of knowledge and experience on me ? 谁能给我照耀知识和经验的光芒? Thanks a lot. 非常感谢。

cron is running crontab(5) entries from the home directory of the user. cron从用户的主目录运行crontab(5)条目。

You need to change appropriately the directory ie to call the chdir(2) syscall (either thru the cd shell builtin, or inside your python script using os.chdir ). 您需要适当地更改目录,即调用chdir(2) syscall(通过内置的cd shell或使用os.chdir在python脚本内部 )。

You should query the current directory (using getcwd(3) , or the pwd command, or the os.getcwd in Python) in your script. 您应该在脚本中查询当前目录(使用getcwd(3)pwd命令或Python中的os.getcwd )。

Also check your PATH if running commands. 如果正在运行命令,还请检查您的PATH

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

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