如何自动将命令行输入馈入python程序

时间:2020-08-21 10:12:57

标签: python input

我继承了由其他人制作的程序,该程序使用以下语法来努力实现“交互式”:

x = input("What is the value of x")

在嵌套的input块中有数十个if语句。要开始重构该程序,我需要设置一些基准测试,以覆盖整个代码并自动输入用户输入的所有组合。

让程序通过python脚本接受用户输入的快速方法是什么?

编辑

我已经尝试使用pexpect的Windows替代方法,该方法似乎可以正常工作。

import wexpect

child = wexpect.spawn('python input_script.py')
child.expect('input x')
child.sendline('5')

测试文件input_script.py如下:

x = input('input x')
print('{} was your input'.format(x))

调用者脚本似乎以退出代码0运行,因此没有错误。但是,我希望有一种方法可以查看 all 的标准输出,包括“已发送的行”。我尝试放置child.beforechild.after,但无法显示整个输出。

3 个答案:

答案 0 :(得分:1)

一种可能性是使用内置的unittest.mock模拟input函数:

import builtins
from unittest.mock import patch
with patch('builtins.input') as input_mock:
    input_mock.side_effect = [
        'Input 1',
        'Input 2',
        'Input 3',
    ]
    print(input('First input'))
    # Input 1
    print(input())
    # Input 2
    print(input('Last one'))
    # Input 3

答案 1 :(得分:0)

您几乎没有选择:

  • 加载配置文件
  • 使用cli参数(sys.argv)
  • 使用环境变量(os.getenv(..))

我会从呼叫者那里得到1个输入。此输入指向保存您需要的其余输入的配置文件(json,yaml,ini)。 因此,您将更改代码的逻辑,并仅在可以在配置中进行数据输入时才询问用户输入。 示例:

size = config.get('size')
size = size if size is not None else input('type the size please')

如果您要完全替换 input(),则可以使用以下代码。

import sys
config = {'type size please:':12}

def input(prompt):
  value = config.get(prompt)
  if value is not None:
    return value
  else:
    print(prompt)
    return sys.stdin.readline()

size = input('type size please:')
print(size)
number = input('type number please:')
print(number)

答案 2 :(得分:0)

我最终使用的解决方案是这样的:

呼叫者脚本:

from subprocess import Popen, PIPE, STDOUT
import sys
user_input = ['John', '555']

communicate_argument = '\n'.join(user_input)
p = Popen([sys.executable, 'example2.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, encoding='utf-8')

stdout, stderr = p.communicate(communicate_argument)

print(stdout)

调用脚本:

name = input('What is your name\n')
age = input('What is your age\n')

print('You are {}, and you are {} years old'.format(name, age))

我觉得这足够简单和通用,因此我可以用不同的方式快速运行程序。不幸的是,我无法让用户输入本身显示在stdout中,但我暂时将不得不接受它。

相关问题