提示问题生成器
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
所以它是:
- 如何从终端获取提示字符串并基于它进行过滤?
- 如何在Python中回答多个提示问题?
我做了一些搜索,但发现大多数问题都是针对 shell 脚本 echo yes | ./script
,做得不多in python
非常感谢
最佳答案
按照评论中的建议,使用 pexpect
。
参见pexpect on github , the official docs和 this handy python for beginners walkthrough on pexpect .
举个例子。假设这是您的 x.sh
文件:
#!/bin/bash
echo -n "Continue? [Y/N]: "
read answer
if [ "$answer" != "${answer#[Yy]}" ]; then
echo -n "continuing.."
else
echo -n "exiting.."
fi
你可以这样做:
import os, sys
import pexpect
# It's probably cleaner to use an absolute path here
# I just didn't want to include my directories..
# This will run x.sh from your current directory.
child = pexpect.spawn(os.path.join(os.getcwd(),'x.sh'))
child.logfile = sys.stdout
# Note I have to escape characters here because
# expect processes regular expressions.
child.expect("Continue\? \[Y/N\]: ")
child.sendline("Y")
child.expect("continuing..")
child.expect(pexpect.EOF)
print(child.before)
Python 脚本的结果:
Continue? [Y/N]: Y
Y
continuing..
尽管我不得不说,如果您有能力编辑它,则将 pexpect 与 bash 脚本一起使用有点不寻常。编辑脚本使其不再提示会更简单:
#!/bin/bash
echo -n "Continue? [Y/N]: "
answer=y
if [ "$answer" != "${answer#[Yy]}" ]; then
echo "continuing.."
else
echo "exiting.."
fi
然后您就可以随意使用 subprocess
来执行它。
import os
import subprocess
subprocess.call(os.path.join(os.getcwd(),"x.sh"))
或者如果您希望输出作为变量:
import os
import subprocess
p = subprocess.Popen(os.path.join(os.getcwd(),"x.sh"), stdout=subprocess.PIPE)
out, error = p.communicate()
print(out)
我意识到这对您来说可能不可能,但值得注意。
关于python 动态回答终端提示是/否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265439/