When I execute my python script from the command line I have no problems like so:
[rv@med240-183 db]$ python formatdb.py
[rv@med240-183 db]$
When I try to use crontab to run the script every midnight I get a series of errors:
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 2: from: command not found
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 3: from: command not found
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: syntax error near
unexpected token `('
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: `conx = MySQLdb.connect
(user = 'root', passwd = '******', db = 'vaxijen_antigens')'
The directory of my script is as follows:
/home/rv/ncbi-blast-2.2.23+/db/
Crontab looks like:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/bin/python/:/home/rv/ncbi-blast-2.2.23+/database_backup:/home/rv/ncbi-blast-2.2.23+/db/
MAILTO="******"
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * command to be executed
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/database_backup/backup.py
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/db/formatdb.py
and my python script looks like:
import MySQLdb
from subprocess import call
from subprocess import Popen
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('vdatabase.fasta', 'w')
for i in row:
f.write('>'+i[0].strip()+'\n')
#f.write(i[1].strip().replace(' ','')+'\n')
s = re.sub(r'[^\w]','',str(i[1]))
s = ''.join(s)
for k in range(0, len(s), 60):
f.write('%s\n' % (s[k:k+60]))
f.write('\n')
f.close
Popen(["formatdb", "-p", "T", "-i", "vdatabase.fasta"]).wait()
You should use Cron any time you want to automate something, like an OS job or a Python script. Needless to say, but an automated Python script can do basically anything. On Linux and macOS, the Crontab consists of six fields.
One of the most frequent causes for the crontab job not being correctly executed is that a cronjob does not run under the user's shell environment. Another reason can be – not specifying the absolute path of the commands used in the script.
Add
#!/usr/bin/env python
to the beginning of your script - right now it's trying to execute your script as a bash, that line says "I'm a python script, please use the right interpreter". It's also called a hash-bang line, but it needs to be the first line in your script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With