Python子进程Popen没有向shell发送所有参数

时间:2012-05-07 23:30:10

标签: python subprocess popen

我正在使用Python的子进程模块来启动另一个程序。该程序需要一个参数'-c {0-7}'。

this_dir = os.path.dirname(os.path.abspath(__file__))
cmd = [os.path.join(this_dir,'foobar'),'-c%d' % channel]
print "Starting process: %s" % str(cmd)
Proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)

在C ++程序中,我正在检查传入的参数:

for (int i = 0; i < argc; i++)
{   
    cerr << i << "   " << argv[i] << endl;
}   
cerr << "" << endl;

这是我运行python脚本时的输出:

user@home:~/embedded_pqa/saleae$ ./foobar.py -c3
Starting process: ['/home/user/code/foobar', '-c3']
0   /home/user/code/foobar

很明显,参数'-c3'没有传递给子进程。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

问题在于shell=True。引用the docs

  

在Unix上,shell = True:[...]如果args是一个序列,第一项指定命令字符串,任何其他项将被视为shell本身的附加参数。

这意味着它调用以下命令:

sh -c /home/user/code/foobar -c3

shell将其解释为命令/home/user/code/foobar和另一个shell参数-c3

只是摆脱shell=True,因为你还没有使用任何sh功能,而且你自己也在使用已经分开的参数列表。

相关问题