简体   繁体   English

从python3脚本中,如何将字符串传递到bash程序中?

[英]From a python3 script, how to I pipe a string into a bash program?

As an example, here's what I've tried: 例如,这是我尝试过的:

#!/usr/bin/env python3

from subprocess import Popen

message = "Lo! I am up on an ox."
Popen('less', shell=True).communicate(input=message)

As the last line, I also tried: 作为最后一行,我还尝试了:

Popen('less', stdin=message, shell=True)

I can do what I want with: 我可以做我想做的事:

Popen('echo "%s" | less' % message, shell=True)

Is there a more pythonic way of doing it? 还有更Python化的方法吗?

Thanks! 谢谢!

@hyades answer above is certainly correct, and depending on what exactly you want might be best, but the reason your second example didn't work is because the stdin value must be file-like (just like unix). 上面的@hyades答案当然是正确的,并且取决于您想要的是什么,这可能是最好的,但是第二个示例不起作用的原因是因为stdin值必须类似于文件(与unix一样)。 The following also works for me. 以下内容也适用于我。

with tempfile.TemporaryFile(mode="w") as f:
     f.write(message)
     f.seek(0)
     Popen("less", stdin=f) 
import subprocess
p = subprocess.Popen('less', shell=True, stdout = subprocess.PIPE, stdin = subprocess.PIPE)
p.stdin.write('hey!!!'.encode('utf-8'))
print(p.communicate())

You can set up a PIPE for communication with the process 您可以设置一个PIPE与流程进行通信

It is enough to add stdin=subprocess.PIPE (to redirect child's stdin) as @hyades suggested and universal_newlines=True (to enable text mode) to your code in order to pass a string to the child process: 只需在代码中添加stdin=subprocess.PIPE subprocess.PIPE (重定向子标准输入)作为@hyades建议,并将universal_newlines=True (启用文本模式)添加到代码中,即可将字符串传递给子进程:

#!/usr/bin/env python
from subprocess import Popen, PIPE

message = "Lo! I am up on an ox."
Popen(['cat'], stdin=PIPE, 
      universal_newlines=True).communicate(input=message)

Don't use shell=True unless you have a reason. 除非有原因,否则不要使用shell=True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM