【问题标题】:Python subprocess Popen not sending all arguments to shellPython子进程Popen没有将所有参数发送到shell
【发布时间】:2012-05-07 23:30:10
【问题描述】:

我正在使用 Python 的 subprocess 模块来启动另一个程序。该程序需要一个参数“-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”没有传递给子进程。有什么想法吗?

【问题讨论】:

  • stracetruss 这样的工具是正确的,可以查看实际传递给execve 系统调用的内容。另外,shell=True 是邪恶的;如果您想控制参数的传递方式,请不要使用它。

标签: python subprocess popen


【解决方案1】:

问题在于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 功能,而且您自己使用的是已经分离的参数列表。

【讨论】:

  • 感谢您的帮助。 shell=True 是罪魁祸首。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
相关资源
最近更新 更多