【发布时间】:2015-05-08 07:58:21
【问题描述】:
我需要在 python 中实现一个过滤器,它从 Linux 命令行字典工具中挑选出特定的输出。我需要:
- 从文件中获取一组单词
- 查找每个单词: 1) 如果单词不包含,则跳过它; 2) else 如果是动词,保存定义。
为了测试代码,我写了两个python文件:
# name.py
import sys
while True:
print 'name => Q: what is your name?'
sys.stdout.flush()
name = raw_input()
if name == 'Exit':
break
print 'name => A: your name is ' + name
sys.stdout.flush()
# test.py
import subprocess
child = subprocess.Popen(r'python name.py',
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
shell = True)
commandlist = ['Luke\n', 'Mike\n', 'Jonathan\n', 'Exit\n']
for command in commandlist:
child.stdin.write(command)
child.stdin.flush()
output = child.stdout.readline()
print 'From PIPE: ' + output
while child.poll() is None:
print 'NOT POLL: ' + child.stdout.readline()
child.wait()
输出是
From PIPE: name => Q: what is your name?
From PIPE: name => A: your name is Luke
From PIPE: name => Q: what is your name?
From PIPE: name => A: your name is Mike
# these lines need to start with "From PIPE" ...
NOT POLL: name => Q: what is your name?
NOT POLL: name => A: your name is Jonathan
NOT POLL: name => Q: what is your name?
NOT POLL:
在while 循环而不是test.py 中的for 循环期间读取后面的输出。是什么原因?
由于需求,每次输入新命令时我都需要获取整个输出。这似乎是一个对话会话。所以subprocess.communicate() 在那里没用,因为它总是终止当前的子进程。如何实现这个需求?
【问题讨论】:
标签: python subprocess