1

我的问题是 cronjob 似乎运行良好,但没有在 .sh 文件中正确执行代码,请参阅下面的详细信息。

我输入 crontab -e,调出 cron: 在该文件中:

30 08 * * 1-5 /home/user/path/backup.sh
45 08 * * 1-5 /home/user/path/runscript.sh >> /home/user/cronlog.log 2>&1

备份.sh:

#!/bin/sh
if [ -e "NEW_BACKUP.sql.gz" ]
then
    mv "NEW_BACKUP.sql.gz" "OLD_BACKUP.sql.gz"
fi
mysqldump -u username -ppassword db --max_allowed_packet=99M | gzip -9c > NEW_BACKUP.sql.gz

运行脚本.sh:

#!/bin/sh
python /home/user/path/uber_sync.py

uber_sync.py:

import keyword_sync
import target_milestone_sync
print "Starting Sync"
keyword_sync.sync()
print "Keyword Synced"
target_milestone_sync.sync()
print "Milestone Synced"
print "Finished Sync"

问题是,它似乎在 uber_sync 中执行打印语句,但实际上并没有执行 import 语句中的代码......有什么想法吗?

另请注意,keyword_sync 和 target_milestone_sync 与 uber_sync 位于同一目录下,即 /home/user/path

感谢您的任何帮助。

4

1 回答 1

1

您的导入语句失败,因为 python 无法找到您的模块。将它们添加到您的搜索路径,然后导入您的模块,如下所示(将其添加到 uber_sync.py):

import sys
sys.path.append("/home/user/path")
import keyword_sync
import target_milestone_sync

Python looks for modules in the current directory (the dir the code is executed in), in the $PYTHONPATH environment variable and config files. This all ends up in sys.path which can be edited like any list object. If you want to learn more about the reasons a certain module gets imported or not i suggest also looking into the standard module imp.

In your case you tested your code in /home/user/path via python uber_sync.py and it worked, because your modules were in the current directory. But when execute it in some/other/dir via python /home/user/path/uber_sync.py the current dir becomes some/other/dir and your modules are not found.

于 2012-05-07T13:33:08.573 回答