shell python在终端提示符下动态回答yes/no

sg24os4d  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(107)

提示问题生成器

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
非常感谢

pbwdgjma

pbwdgjma1#

如注解中所建议的,使用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..


尽管我不得不说,如果你有能力编辑它,那么在bash脚本中使用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)


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

相关问题