我试图使用带有args的python subprocess.call来调用shell脚本。我没有将args传递给shell脚本,但是脚本被调用没问题。这就是我所拥有的
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 :(得分: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'
修改:而不是使用call
和p.stdout.read
,您应该使用Popen().communicate
,这是为此目的而做的,它有助于避免死锁。
编辑²(上面的编辑回答):
cmd = ' '.join([cmd, args])
(out, err) = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, shell=True).communicate(None)
您必须将完整的命令行传递给Popen
。 communicate
的参数将写入process.stdin
(process
= Popen
返回)。