使用python子进程运行ant脚本时出错

使用python子进程运行ant脚本时出错,python,ant,subprocess,Python,Ant,Subprocess,我正在尝试使用python子流程运行ant作业。下面是我试图执行的命令 ant -f ../lib/java/build.xml -Dno-gen-thrift="" -Dtestargs "--protocol=binary --transport=buffered" run-testserver 但是当我使用下面的命令使用子进程运行这个程序时 subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-

我正在尝试使用python子流程运行ant作业。下面是我试图执行的命令

ant -f ../lib/java/build.xml -Dno-gen-thrift="" -Dtestargs "--protocol=binary --transport=buffered" run-testserver
但是当我使用下面的命令使用子进程运行这个程序时

subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-Dtestargs \"--protocol=binary --transport=buffered\"','run-testserver'])
我在说“未知参数:--transport=buffered”时出错

这里的'--protocol=binary'和'--transport=buffered'是解析为使用此ant脚本执行的java类的命令行参数。 当我只发送一个参数时,下面的命令也可以正常运行

subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-Dtestargs \"--protocol=binary\"','run-testserver'])

subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-Dtestargs \"--transport=buffered\"','run-testserver'])

原因是什么?

在原来的命令行中,您可以直接在shell中运行

-Dtestargs "--protocol=binary --transport=buffered"
实际上是两个命令行参数。shell解析第二个参数的外部双引号,并提供字节字符串
--protocol=binary--transport=buffered
,作为ant可执行文件的参数。Ant不再看到双引号了。您应该在
子流程
中复制相同的内容,而不是将
'-Dtestargs\'--protocol=binary--transport=buffered\'
作为包含双引号的单个参数提供。提供两个独立的参数,即两个列表项,一个是
'-Dtestargs'
,另一个是
'--protocol=binary--transport=buffered'

老实说,这只是一个有根据的猜测,但我很肯定这是你的问题的一部分


另外,您应该注意到,命令行解析可能是一个非常微妙的问题。参数通过不同的层,这些层可能彼此都不知道。例如,当您通过shell运行Python命令时,shell首先使用特定方法解析参数,将它们提供给CPython可执行文件,CPython可执行文件使用特定方法再次解析参数,然后Python应用程序代码使用特定方法再次解析参数。在您的例子中,Python的子流程模块在使用系统调用生成新流程之前使用特定方法创建参数数据,这将引入更复杂的功能。总而言之,结果可能是意外的行为,您可能必须调整命令行,以使Ant理解正确的事情。这可能会很棘手。

当我使用下面的

subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-Dtestargs', '\"--protocol=binary', '--transport=buffered\"','run-testserver'])

另外,
-Dno gen thrift=“”
可能应该翻译成
'-Dno gen thrift',“
在Python中不需要在单引号内转义双引号:
shlex.split('-Dno gen thrift”“-Dtestargs”--协议=二进制--传输=缓冲“)
,正如J.F.塞巴斯蒂安指出的那样,无需使用单引号终止符转义字符串文字中的双引号。你试过我的建议了吗?“--protocol=binary--transport=buffered”,因为一个论点对我不起作用
subprocess.call(['ant','-f','lib/java/build.xml','-Dno-gen-thrift=\"\"','-Dtestargs', '\"--protocol=binary', '--transport=buffered\"','run-testserver'])