[英]Subprocess writing stdin and reading stdout python 3.4
I am writing a script which would run a Linux command and write a string (up to EOL) to stdin and read a string (until EOL) from stdout. 我正在编写一个脚本,该脚本将运行Linux命令并写入一个字符串(最多EOL)到stdin,并从stdout读取一个字符串(直到EOL)。 The easiest illustration would be
cat -
command: 最简单的例子是
cat -
命令:
p=subprocess.Popen(['cat', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stringin="String of text\n"
p.stdin.write=(stringin)
stringout=p.stout.read()
print(stringout)
I aim to open the cat -
process once and use it to write a string multiple times to its stdin every time getting a string from its stdout. 我的目标是打开
cat -
处理一次,并在每次从stdout获取字符串时使用它多次向其stdin写一个字符串。
I googled quite a bit and a lot of recipes don't work, because the syntax is incompatible through different python versions (I use 3.4). 我在Google上搜索了很多,并且很多食谱都不起作用,因为该语法在不同的python版本中不兼容(我使用3.4)。 That is my first python script from scratch and I find the python documentation to be quite confusing so far.
那是我从头开始编写的第一个python脚本,到目前为止,我发现python文档非常混乱。
Thank you for your solution Salva. 感谢您的解决方案Salva。 Unfortunately
communicate()
closes the cat -
process. 不幸的是,
communicate()
关闭了cat -
进程。 I did not find any solution with subprocess
to communicate with the cat -
without having to open a new cat -
for every call. 对于每次调用,我都没有找到与
subprocess
cat -
进行通讯的任何解决方案,而无需打开新的cat -
。 I found an easy solution with pexpect though: 我用pexpect找到了一个简单的解决方案:
import pexpect
p = pexpect.spawn('cat -')
p.setecho(False)
def echoback(stringin):
p.sendline(stringin)
echoback = p.readline()
return echoback.decode();
i = 1
while (i < 11):
print(echoback("Test no: "+str(i)))
i = i + 1
In order to use pexpect
Ubuntu users will have to install it through pip
. 为了使用
pexpect
Ubuntu用户必须通过pip
安装它。 If you wish to install it for python3.x, you will have to install pip3 (python3-pip) first from the Ubuntu repo. 如果要为python3.x安装它,则必须首先从Ubuntu存储库中安装pip3(python3-pip)。
Well you need to communicate with the process: 那么您需要与流程进行沟通 :
from subprocess import Popen, PIPE
s = Popen(['cat', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
input = b'hello!' # notice the input data are actually bytes and not text
output, errs = s.communicate(input)
To use unicode strings, you would need to encode()
the input and decode()
the output: 要使用unicode字符串,您需要
encode()
输入进行encode()
并对输出进行decode()
:
from subprocess import Popen, PIPE
s = Popen(['cat', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
input = 'España'
output, errs = s.communicate(input.encode())
output, errs = output.decode(), errs.decode()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.