如何为Python的“输入"功能生成键盘输入? [英] How can I generate keyboard inputs for Python's 'input' function?
问题描述
我有一个用Python编写的控制台程序.我想在自动测试例程中测试几种输入组合.通过Python的 input(...)
函数读取输入.
I have a console program written in Python. I would like to test several input combinations in an automatic test routine. The input is read via Pythons input(...)
function.
- 如何模拟键盘或任何其他输入流,以将单个字符或字符串发送到
input
? - 还是我需要用连接到我的测试用例的另一个函数替换输入?
推荐答案
如果这只是一个测试用例,而不是大系统的真正组成部分",则意味着您只需要将某些输入传递给命令行可执行文件即可(例如运行测试)并且您正在使用Unix,一种便捷的方法是使用管道:
If that is just a test case and not a "real part of big system" - meaning that you just need to pass a certain input to your command line executable ones (e.g. run test) and you are using Unix, one convenient way of doing this is using pipes:
// read.py
val = raw_input()
print 'nice', val
然后通过控制台:
$ echo "hat" | python read.py
nice hat
Windows语法上的
on Windows syntax is little different - should be something like
dir> python.exe read.py < file.txt
实现相同目标的另一种简单易行的方法是用自定义流对象替换 sys.stdin
:
One other hacky-simple way to achieve same thing is to replace sys.stdin
with a custom stream object:
sys.stdin = StringIO.StringIO("line 1\nline 2\nline 3")
但是,如果这比自动执行例行程序要大的多,或者使用固定的测试集测试学生的家庭作业,则应该考虑使用@erip的答案.
One should consider using @erip 's answer if that is something bigger than a automatisation routine or testing students' home assignments against fixed set of tests, though.
这篇关于如何为Python的“输入"功能生成键盘输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!