【问题标题】:Python - Read terminal output and give input from the script itselfPython - 读取终端输出并从脚本本身提供输入
【发布时间】:2020-03-08 17:27:02
【问题描述】:

我正在使用一个模块中的一个类,它在第一次使用时会要求我在终端中输入一些内容。

在每个新实例中,终端都会要求一些输入。

例子:

instance = Class()
instance.run()
## asks for input in the terminal

我考虑了 subprocess 模块,但没有找到任何关于我的用例的信息,最好的解决方案应该允许我阅读它的要求并在每个步骤中输入一些数据。

提前致谢

【问题讨论】:

  • 你能分享一下你正在使用什么类和模块吗?使用 subprocess 模块,您可以将管道设置为标准输入,这可能会有所帮助。但是,根据类/模块,Python 可能有更简单的方法。

标签: python python-3.x subprocess stdout stdin


【解决方案1】:

这是来自a fun guide I found on google just now 的示例。

我建议您搜索有关此主题的几篇不同文章,以了解可能在您的特定情况下对您有所帮助的不同方法。编码愉快!

from __future__ import print_function, unicode_literals
from PyInquirer import prompt
from pprint import pprint
questions = [
    {
        'type': 'input',
        'name': 'first_name',
        'message': 'What\'s your first name',
     }
]
answers = prompt(questions)
pprint(answers)
)

【讨论】:

    【解决方案2】:

    您的问题实际上在这里得到了很好的回答: Write function result to stdin

    我在下面提供了一个选项,但总的来说这是一个非常混乱的情况,我会寻找替代解决方案。甚至猴子修补其他库以接受输入作为变量可能会更干净。

    话虽如此,您的翻译可能如下所示:

    import sys
    import StringIO
    
    class Foo(object):
        def run(self):
            self.x = raw_input('Enter x: ')
    
    old_stdin = sys.stdin
    instance = Foo()
    sys.stdin = StringIO.StringIO('asdlkj')
    instance.run()
    print
    print 'Got: %s' % instance.x
    

    并运行:

    Enter x: 
    Got: asdlkj
    

    【讨论】: