从python3脚本,我如何将字符串管道传输到bash程序



作为一个例子,以下是我尝试过的:

#!/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)

有没有更像蟒蛇的方式?

谢谢!

上面的

@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以与进程进行通信

只需按照@hyades的建议将stdin=subprocess.PIPE(重定向子进程的stdin)和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

最新更新