简体   繁体   中英

Cronjob - Running Scripts and Python

My problem is that the cronjob seems to be running fine, but not executing the code properly within the .sh files, please see below for details.

I type crontab -e, to bring up cron: In that file:

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

backup.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

runscript.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"

The problem is, it seems to do the print statements in uber_sync, but not actually execute the code from the import statements... Any ideas?

Also note that keyword_sync and target_milestone_sync are located in the same directory as uber_sync, namely /home/user/path

Thank you for any help.

Your import statements fail because python can not locate your modules. Add them them to your search path and then import your modules, like this (add this to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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