繁体   English   中英

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

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

例如,这是我尝试过的:

#!/usr/bin/env python3

from subprocess import Popen

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

作为最后一行,我还尝试了:

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

我可以做我想做的事:

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

还有更Python化的方法吗?

谢谢!

上面的@hyades答案当然是正确的,并且取决于您想要的是什么,这可能是最好的,但是第二个示例不起作用的原因是因为stdin值必须类似于文件(与unix一样)。 以下内容也适用于我。

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

您可以设置一个PIPE与流程进行通信

只需在代码中添加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)

除非有原因,否则不要使用shell=True

暂无
暂无

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

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