Running Python file from crontab

This is the place for queries that don't fit in any of the other categories.

Running Python file from crontab

Postby shahriyar.r » Thu Jan 30, 2014 5:50 am

Dear All ,

I have an issue with running python script from crontab.
Here is a general idea:
i have written a very simple python script for oracle expdp , backup tool.
My Code:

Code: Select all
import os
import datetime
import subprocess
import shlex

now = datetime.datetime.now()


file_name = 'pashadev_'+str(now.day)+'_'+str(now.month)+'_'+str(now.year)+'_'+str(now.hour)+'_'+str(now.minute)+'_'+str(now.second)

comm = 'expdp'
connection = 'nazir/nazir'
schema = 'pashadev'
dump_file = file_name+'.dmp'
log_file = file_name+'.log'

command = '%s %s schemas=%s directory=data_pump_directory dumpfile=%s logfile=%s' % (comm, connection, schema, dump_file, log_file)
command = shlex.split(command)
cm = subprocess.Popen(command, stdout=subprocess.PIPE)
print str(cm.stdout.read())


Here is my crontab for executing this script:

Code: Select all
39 9 * * * /usr/bin/python /home/oracle/Dumps/dump.py 2>&1 >> /home/oracle/cron7


With this output in /home/oracle/cron7 file is empty. It generates nothing.

But when i comment out exactly "subprocess command runner" code.. it works:

Code: Select all
import os
import datetime
import subprocess
import shlex

now = datetime.datetime.now()


file_name = 'pashadev_'+str(now.day)+'_'+str(now.month)+'_'+str(now.year)+'_'+str(now.hour)+'_'+str(now.minute)+'_'+str(now.second)

comm = 'expdp'
connection = 'nazir/nazir'
schema = 'pashadev'
dump_file = file_name+'.dmp'
log_file = file_name+'.log'

#command = '%s %s schemas=%s directory=data_pump_directory dumpfile=%s logfile=%s' % (comm, connection, schema, dump_file, log_file)
#command = shlex.split(command)
#cm = subprocess.Popen(command, stdout=subprocess.PIPE)
#print str(cm.stdout.read())

print dump_file



and output in /home/oracle/cron7 appears:

pashadev_30_1_2014_9_39_1.dmp

So why subprocess command doesnt work from crontab? or what is problem in general here?
shahriyar.r
 
Posts: 7
Joined: Thu Aug 29, 2013 9:50 am

Re: Running Python file from crontab

Postby metulburr » Sat Feb 01, 2014 4:46 pm

the output failed for me as well. I had to add the shebang line, make the file executable,modifiy the communicate line, and then it worked in crontab

Code: Select all
cm = subprocess.Popen('/usr/bin/uptime'.split(), stdout=subprocess.PIPE)
#print str(cm.stdout.read())
output = cm.communicate()[0].decode()
print(output)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: snippsat and 1 guest