【问题标题】:Wrong path results the python program runs using crontab错误的路径导致python程序使用crontab运行
【发布时间】:2013-01-30 22:57:34
【问题描述】:
我在 Linux 下的 python 中有一个脚本,需要确定当前工作目录。执行此操作的程序部分是:
import os
cwd = os.getcwd()
print cwd
当我运行程序时,它给了我正确的答案:
/home/johny/LST/CT
但是当我使用 crontab 运行它时,它给了我这个:
/home/johny
即使我将它放在更深的文件夹中,也会产生相同的路径。有人知道可能是什么问题吗?
【问题讨论】:
标签:
python
linux
python-2.7
cron
crontab
【解决方案1】:
在你的 crontab 文件中:
1 0 * * * cd /home/johny/LST/CT; python your_script.py
【解决方案2】:
cron 可能只是将自己设置为您的主目录。如果您需要脚本在特定目录中运行,请考虑使用类似
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
在你的脚本的顶部,虽然你的脚本实际上不应该关心它从哪里运行。脚本中的所有文件路径都应该是相对于脚本的,使用类似:
scriptdir = os.path.dirname(os.path.abspath(__file__))
mypath = os.path.join(scriptdir, 'data', 'mfile.dat')
... etc ...