python 动态回答 yes/no 终端提示

python dynamically answer yes/no to terminal prompt

提示问题生成器

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()

于是得出:

  1. 如何从终端获取提示字符串并根据它进行过滤?
  2. 如何回答python中的多个提示问题?

我进行了一些搜索,但发现大多数问题都是针对 shell 脚本 echo yes | ./script,没有做太多 in python

非常感谢

按照评论中的建议,使用pexpect

pexpect on github, the official docs and 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)

我知道这对你来说可能是不可能的,但值得注意。