提示问题生成器
class SynthesisPromptGenerator:
def wait_key(self):
''' Wait for a key press on the console and return it. '''
result = None
for singlePrompt in ["questionCat", "questionDog"]:
try:
result = raw_input(singlePrompt)
print 'input is: ', result
except IOError:
pass
return result
字符串
我有一个PromptGenerator,它将生成多个终端提示问题,在回答第一个问题后,第二个问题将弹出,如
questionCat
(and wait for keyboard input)
questionDog
(and wait for keyboard input)
型
我的目标是自动和动态地回答问题
class PromptResponder:
def respond(self):
generator = SynthesisPromptGenerator()
child = pexpect.spawn(generator.wait_key())
child.expect("\*Cat\*")
child.sendline("yes")
child.expect("\*Dog\*")
child.sendline("no")
child.expect(pexpect.EOF)
if __name__ == "__main__":
responder = PromptResponder()
responder.respond()
型
- 如果提示问题包含
Cat
,则回答yes
- 如果提示问题包含
Dog
,则回答no
所以它是:
1.如何从终端获取提示字符串并根据它进行过滤?
1.如何在Python中回答多个提示问题?
我做了一些搜索,但发现大多数问题都是针对shell脚本echo yes | ./script
的,很少做in python
非常感谢
1条答案
按热度按时间pbwdgjma1#
如注解中所建议的,使用
pexpect
。参见pexpect on github、the official docs和this handy python for beginners walkthrough on pexpect。
举个例子。假设这是您的
x.sh
文件:字符串
你可以这样做:
型
python脚本的结果:
型
尽管我不得不说,如果你有能力编辑它,那么在bash脚本中使用pexpect有点不寻常。更简单的做法是编辑脚本,使其不再提示:
型
然后你可以自由地使用
subprocess
来执行它。型
或者,如果您希望将输出作为变量:
型
我知道这对你来说可能是不可能的,但值得注意。