python动态回答是/否终端提示

时间:2018-05-10 04:22:57

标签: python bash shell automation command-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()
  • 如果提示问题包含Cat,则回答yes
  • 如果提示问题包含Dog,则回答no

所以它来了:

  1. 如何从终端获取提示字符串并根据它进行过滤?
  2. 如何在python中回答多个提示问题?
  3. 我做了一些搜索,但发现大多数问题都是针对shell脚本echo yes | ./script,而不是很多in python

    非常感谢

1 个答案:

答案 0 :(得分:1)

根据评论中的建议,使用pexpect

请参阅pexpect on githubthe official docsthis 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..

虽然我必须说如果你有能力编辑它,使用px脚本使用pexpect有点不合时宜。编辑脚本会更简单,以便它不再提示:

#!/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)

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