Python subprocess passes one argument only

2019-09-05 20:08发布

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()

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

2条回答
相关推荐>>
2楼-- · 2019-09-05 20:34

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

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

Update

Always prefer;

  • shell=False (the default) to shell=True and pass an array of strings; and
  • an absolute path to the executable, not a relative path.

I.e.;

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

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'])
查看更多
仙女界的扛把子
3楼-- · 2019-09-05 20:40

Don't use shell=True:

p = subprocess.Popen(["./myapp","-p","s"])
p.communicate()
查看更多
登录 后发表回答