Python 子进程只传递一个参数 [英] Python subprocess passes one argument only

查看:40
本文介绍了Python 子进程只传递一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 脚本 (2.7),用于调用外部进程.直到最近它运行良好.

I have a Python script (2.7) which I use to invoke an external process.Till recently it worked fine.

但是现在当我运行它时,我看到它没有传递进程参数.我还调试了被调用的进程,它只接收单个参数(进程可执行文件的路径).

But now when I run it I see it doesn't pass over process arguments.I have also debugged the invoked process and it receives only the single argument (the path of the process executable).

p = subprocess.Popen(["./myapp","-p","s"],shell=True)
p.communicate()

上述代码的执行只传递了myapp"作为命令参数.为什么会发生这种情况?

Execution of the above code passes only "myapp" as the command argument.Why could that happen?

推荐答案

使用 shell=True 时,只传递一个字符串(不是列表);

When using shell=True, just pass a string (not a list);

p = subprocess.Popen('./myapp -p s', shell=True)
p.communicate()

更新

总是喜欢;

  • shell=False(默认)到 shell=True 并传递一个字符串数组;和
  • 可执行文件的绝对路径,而不是相对路径.
  • shell=False (the default) to shell=True and pass an array of strings; and
  • an absolute path to the executable, not a relative path.

即;

with subprocess.Popen(['/path/to/binary', '-p', 's']) as proc:
    stdout, stderr = proc.communicate()

如果您只对 stdout(而不是 stderr)感兴趣,请选择上述解决方案(它更安全、更短):

If you're just interested in the stdout (and not the stderr), prefer this to the above solution (it's safer and shorter):

stdout = subprocess.check_output(['/path/to/binary', '-p', 's'])

这篇关于Python 子进程只传递一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆