简体   繁体   中英

Trying to run a python script with crontab every hour, but one section of the python code does not execute

I wrote a script using python and selenium that tries to register for a class called puppy play. Crontab runs the script every hour and sends any output to a file called "cronpup.log". This section of code is in my python script and it just checks to see if the registration was successful or not then appends the results to the file "pup.log".

# Pup Logger    
f = open("pup.log", "a+")
f.write(time.strftime("%Y-%m-%d %H:%M:%S   "))
if pups == 1:
    f.write("Pups!\n")
elif pups == 0:
    f.write("No Pups\n")
else:
    f.write("Ruh Roh, Something is wrong\n")
f.close()

This creates the "pup.log" file with entries like the following

$ pup.log
2014-10-17 17:49:18   No Pups
2014-10-17 19:37:28   No Pups

I can run the python script just fine from the terminal, but when crontab executes the script no new entries are made in "pup.log". I've checked the output from crontab and have found nothing. Here is crontab's output

$ cronpup.log
.
----------------------------------------------------------------------
Ran 1 test in 81.314s

OK

It seems like crontab is just ignoring that section of the code, but that seems pretty silly. Any ideas how to get this working?

The line

f = open("pup.log", "a+")

is your problem. Open is looking the the current working directory for pup.log, creating it if necessary, and appending to it. If you run from the terminal while in the same directory as the python script, that's where pup.log will appear. The cwd when running from cron is the home directory of the user the job is running as, so when run from cron it's dropping a pup.log file somewhere else on your system.

You can either hardcode a full path, or use

os.chdir(os.path.dirname(os.path.abspath(__file__)))

to set the current working directory to the directory the python file is in, or modify the above to put pup.log whereever you like.

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