2016-01-15 199 views
0

我正在写一个脚本,它将运行一个Linux命令并将一个字符串(最多EOL)写入标准输入并从标准输出中读取一个字符串(直到EOL)。最简单的例证是cat -命令:写入标准输入和读取标准输出的子进程python 3.4

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) 

我的目标是一旦打开cat -过程,并用它来多次将一个字符串写入其标准输入每一个正从它的标准输出字符串的时间。

我GOOGLE了很多,很多食谱不工作,因为语法是不兼容的通过不同的Python版本(我使用3.4)。这是我从头开始的第一个python脚本,我发现python文档到目前为止是相当混乱的。

回答

0

那么你需要communicate与过程:

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) 

使用Unicode字符串,则需要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() 
2

谢谢您的解决方案萨尔瓦。 不幸的是communicate()关闭了cat -的过程。我没有找到与subprocess的任何解决方案与cat -进行通信,而无需为每个呼叫打开新的cat -。我发现了一个简单的解决方案与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 

为了使用pexpect Ubuntu用户必须通过pip安装它。如果你想为python3.x安装它,你必须首先从Ubuntu repo安装pip3(python3-pip)。

相关问题