2010-07-26 130 views
10

當我在命令行中執行我的Python腳本我有沒有問題,像這樣:的crontab不會運行Python腳本

[RV @ med240-183 DB] $蟒蛇formatdb.py
[RV @ med240 -183分貝] $

當我嘗試使用crontab來運行該腳本每到半夜,我得到了一系列錯誤:

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')' 

我的腳本的目錄如下:

/home/rv/ncbi-blast-2.2.23+/db/

crontab的樣子:

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 

和我的python腳本的樣子:

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() 
+0

你有什麼操作系統? gentoo中的一些類似的錯誤在哪裏,嘗試使用例如這個答案來解決你的問題http://schwobeseggl.de/2009/08/04/gentoo-portage-python/。 你的問題是,當你手動運行它 - 你從X環境啓動它,但cron沒有X服務器工作... – 2010-07-26 17:17:08

回答

27

添加

#!/usr/bin/env python 

到你的腳本開始 - 現在它試圖執行你的腳本作爲bash,該行說「我是一個python腳本,請使用正確的解釋器」。它也被稱爲hash-bang線,但它必須是腳本中的第一行。

+2

噢,我忘了基本知識謝謝提醒我 – Phil 2010-07-26 17:19:43

+5

這發生在我身上幾次 - 就像你我看不到那些明顯的,哎呦。「有時候另一雙眼睛是無價的。 – 2010-07-26 18:00:07

+0

令人敬畏的東西 - 只是添加,shebang線救了我整整一天的頭髮拉。謝謝:) – 2013-05-21 10:56:49