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

标签 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”没有传递给子进程。有什么想法吗?

最佳答案

问题出在 shell=True 上。引用 the docs :

On Unix, with shell=True: […] If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

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

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

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

只需删除 shell=True,因为无论如何您都没有使用任何 sh 功能,而是您自己使用了一个已经分离的参数列表。

关于Python 子进程 Popen 没有将所有参数发送到 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10490529/

相关文章:

python - 如何在 Python 中将 Azure Blob 文件 CSV 转换为 Excel

python - 在 Python 中并行运行多个外部命令

c - popen 函数调用后 sleep 在子进程中不起作用

fork - 是否有 fork 并与 D 中的子进程通信的示例?

cocoa - 如何通过popen发送整数?

python - 我的字典计算字母而不是单词

python - Scapy - 我怎样才能隐藏 sendp\sr1 的报告并只得到最终的报告?

python - 如何使用 subprocess.call 命令在 Linux 终端中输入指向文件路径的字符串?

Python:使用win32com(或其他模块)调整excel文件的打印属性

python - "3-way"Python 子进程管道 : send stdout and stderr to two different processes?