Python-无法调用系统命令

我有一些python代码,我想从中调用另一个程序.该程序将

>将一些输出打印到STDOUT
>将文件写入磁盘

使用通话我得到以下行为;

from subprocess import call
call(['./tango_x86_64_release', 'VTS1 ct="N" nt="N" ph="7.2" te="303" io="0.02" seq="MKHPYEEFPTGSKSPYNMSRGAHPGAV"'])
34, File not properly written, try writing it up again, 
1

无论是否将参数拆分为列表,都会发生这种情况.

call(['./tango_x86_64_release', 'VTS1', 'ct="N"', 'nt="N"', 'ph="7.2"', 'te="303"', 'io="0.02"', 'seq="MKHPYEEFPTGSKSPYNMSRGAHPGAV"'])
34, File not properly written, try writing it up again, 
1

我可以从我的终端上调用相同的命令

./tango_x86_64_release VTS1 ct="N" nt="N" ph="7.2" te="303" io="0.02" seq="MKHPYEEFPTGSKSPYNMSRGAHPGAV"

可行,并且退出状态为0.

好像是写到磁盘上导致了问题,如果我中断命令,则会得到适当的警告消息(即删除参数,它警告我该参数丢失).

使用subprocess.Popen()会产生OSError;

import subprocess as sub
output = sub.Popen('./tango_x86_64_release VTS1 ct="N" nt="N" ph="7.2" te="303" io="0.02" seq="MKHPYEEFPTGSKSPYNMSRGAHPGAV"', stdout=sub.PIPE, stderr=sub.PIPE)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

任何帮助,不胜感激

解决方法:

使用shlex.split为您拆分命令:

import shlex
call(shlex.split('./tango_x86_64_release VTS1 ct="N" nt="N" ph="7.2" te="303" io="0.02" seq="MKHPYEEFPTGSKSPYNMSRGAHPGAV"'))

请注意,尽管您可以通过添加shell = True来解决问题,但应尽可能避免这样做,因为它可以是security risk(搜索“ shell注入”).

上一篇:Android OpenGL ES 开发(一): OpenGL ES 介绍


下一篇:Python子进程.Popen PIPE和SIGPIPE