2012-06-12 125 views
0

我正在嘗試使用python subprocess.call和args來調用shell腳本。我有的參數沒有被傳遞給shell腳本,但腳本被稱爲沒有問題。下面是我有Python subprocess.call帶參數

prepend = str(prepend) 
print "prepend = " + str(prepend) 
filename = str(request.FILES['mdbfile']) 
print "filename = " + str(filename) 
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) 
print "PROJECT_ROOT = " + str(PROJECT_ROOT) 
filename = str(PROJECT_ROOT) + '/%s' % filename 
print "full_filename = " + str(filename) 
cmd = '%s/buildcsvs.sh' % (PROJECT_ROOT) 
print "full_cmd = " + str(cmd) 
p = subprocess.call([cmd, filename, prepend], shell=True) 
output = p.stdout.read() 
print output 

這裏的shell腳本是什麼樣子

#${1} is the file name, ${2} is the prepend code 
echo "mdb-export ${1} TEAM > \"${2}team.csv\"" 
mdb-export ${1} TEAM > "${2}team.csv" 

而這裏的輸出是什麼樣子

prepend = 749176818 
filename = 2011ROXBURY.mdb 
PROJECT_ROOT = /Planner 
full_filename = /Planner/2011ROXBURY.mdb 
full_cmd = /Planner/buildcsvs.sh 
Exception AttributeError: AttributeError("'_DummyThread' object has no attribute '_Thread__block'",) in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored 
mdb-export TEAM > "team.csv" 
Usage: mdb-export [options] <file> <table> 

沒有人有任何想法我什麼做錯了?謝謝你 - 我感謝您的幫助

編輯:現在,我有這樣的:

print "full_cmd = " + str(cmd) 
args = "%s %s" % (filename, prepend) 
print "full_args = " + str(args) 
(out, err) = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate(args) 

,它看起來並不像它的順利完成調用腳本。

你知道爲什麼嗎?

+0

可能與您的問題有關:http://bugs.python.org/issue14308 – 2012-06-12 23:22:28

回答

2

如果傳遞shell=True ARGS必須是一個字符串,而不是一個列表:

In [4]: from subprocess import check_output 

In [5]: check_output(['echo', '123']) 
Out[5]: '123\n' 

In [6]: check_output(['echo', '123'], shell=True) 
Out[6]: '\n' 

In [7]: check_output('echo 123', shell=True) 
Out[7]: '123\n' 

編輯:而不是使用callp.stdout.read你應該使用Popen().communicate的,這是爲了這個目的製成,它有助於避免死鎖。

Edit²(回答上面編輯):

cmd = ' '.join([cmd, args]) 
(out, err) = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, shell=True).communicate(None) 

你有充分的命令行傳遞給Popencommunicate的參數將被寫入process.stdinprocess =返回什麼Popen)。

+0

謝謝 - 希望這會照顧我得到的例外。我已更新帖子,但仍然遇到問題 – mythander889

+0

請參閱我的編輯.... – dav1d

+0

太棒了!謝謝 – mythander889