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

标签 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中回答多个提示问题?

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

非常感谢

最佳答案

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

参见pexpect on github , the 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..

尽管我不得不说,如果您有能力编辑它,则将 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/

相关文章:

mongodb - 为 mongo db 执行 shell 脚本时出现意外标记 "("附近的语法错误

python - "except"语句与参数相同的异常类两次

linux - 具有作业控制的 Bash 进程替换后台

linux - 复制后 bash 脚本无法正常工作

linux - 如何将值列表传递给脚本中的shell参数

bash - 如何在 bash 中进行二进制加法

shell - 如何将Jenkins凭证传递给Dockerfile/Shell?

python - 如何调整 Seaborn 因子图中标签之间的间距

python - 在 Keras 中实现自定义损失函数

Python Linux-复制文件到windows共享盘(samba)