带有子进程Popen的PyInquirer

时间:2019-01-31 07:09:26

标签: python subprocess popen

我的目标很简单,我有两个脚本A和B,它们都使用PyInquirer处理来自用户的输入。

脚本a.py:

from PyInquirer import prompt

    def do():
        questions = [
            {
                'type': 'input',
                'name': 'inputa1',
                'message': 'inputa1',
            }
        ]
        answers = prompt(questions)

        # call b.py

        if output_from_b == 1:
            # do something AAA
        else:
            # do something BBB

    if __name__ == "__main__":
        do()

脚本b.py几乎相同:

from PyInquirer import prompt

def do():
    questions = [
        {
            'type': 'input',
            'name': 'inputb1',
            'message': 'inputb1',
        }
    ]
    answers = prompt(questions)
    return answers["inputb1"]

if __name__ == "__main__":
    do()

您可以看到我想做的是从a.py调用b.py并从b.py获取用户输入,然后继续在a.py中获得输出结果。

我尝试过:

f = os.popen("python3 b.py")

呼叫b.py但出现错误:

Traceback (most recent call last):
  File "b.py", line 27, in <module>
    do()
  File "b.py", line 22, in do
    answers = prompt(questions)
  File "python3.7/site-packages/PyInquirer/prompt.py", line 75, in prompt
    eventloop=eventloop)
  File "python3.7/site-packages/prompt_toolkit/shortcuts.py", line 576, in run_application
    output=create_output(true_color=true_color))
  File "python3.7/site-packages/prompt_toolkit/shortcuts.py", line 126, in create_output
    ansi_colors_only=ansi_colors_only, term=term)
  File "python3.7/site-packages/prompt_toolkit/terminal/vt100_output.py", line 424, in from_pty
    assert stdout.isatty()
AssertionError

我不确定哪里出错了,或者还有其他方法可以解决这个问题。

任何建议将不胜感激,谢谢:)

1 个答案:

答案 0 :(得分:1)

最好的方法是使用这样的方法类:

#import class
classe_call = getattr(importlib.import_module('package.myclassB', 'myclassB')
#create object
myObject = class_call() #you can use param 
#call method
getattr(myObject, do)()