./foo.py < 的 Pythonic 等价物酒吧.png [英] Pythonic equivalent of ./foo.py < bar.png
问题描述
我有一个从 sys.stdin
读取的 Python 程序,所以我可以用 ./foo.py < 调用它.bar.png
.如何从另一个 Python 模块中测试此代码?也就是说,如何在运行测试脚本时将 stdin 设置为指向文件的内容?我不想做类似 ./test.py < 的事情.测试.png
.我不认为我可以使用 fileinput
,因为输入是二进制的,我只想处理一个文件.该文件使用来自 PIL.
I've got a Python program that reads from sys.stdin
, so I can call it with ./foo.py < bar.png
. How do I test this code from within another Python module? That is, how do I set stdin to point to the contents of a file while running the test script? I don't want to do something like ./test.py < test.png
. I don't think I can use fileinput
, because the input is binary, and I only want to handle a single file. The file is opened using Image.open(sys.stdin)
from PIL.
推荐答案
除了用作独立程序之外,您还应该概括您的脚本,以便可以从测试脚本中调用它.这是执行此操作的示例脚本:
You should generalise your script so that it can be invoked from the test script, in addition to being used as a standalone program. Here's an example script that does this:
#! /usr/bin/python
import sys
def read_input_from(file):
print file.read(),
if __name__ == "__main__":
if len(sys.argv) > 1:
# filename supplied, so read input from that
filename = sys.argv[1]
file = open(filename)
else:
# no filename supplied, so read from stdin
file = sys.stdin
read_input_from(file)
如果使用文件名调用它,将显示该文件的内容.否则,将显示从 stdin 读取的输入.(能够在命令行上传递文件名可能对您的 foo.py
脚本很有用.)
If this is called with a filename, the contents of that file will be displayed. Otherwise, input read from stdin will be displayed. (Being able to pass a filename on the command line might be a useful improvement for your foo.py
script.)
在测试脚本中,您现在可以使用文件调用 foo.py
中的函数,例如:
In the test script you can now invoke the function in foo.py
with a file, for example:
#! /usr/bin/python
import foo
file = open("testfile", "rb")
foo.read_input_from(file)
这篇关于./foo.py < 的 Pythonic 等价物酒吧.png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!