假设我想将输入通过管道传输到 Python 程序,然后在命令行上从用户那里获取输入。
echo http://example.com/image.jpg | python solve_captcha.py
和内容solve_captcha.py
are:
import sys
image_url = sys.stdin.readline()
# Download and open the captcha...
captcha = raw_input("Solve this captcha:")
# do some processing...
以上将触发EOFError: EOF when reading a line
error.
我也尝试添加sys.stdin.close()
行,这提示了ValueError: I/O operation on closed file
.
你能通过管道将信息传递给stdin
然后再从用户那里获取输入?
Note:这是一个精简的、简化的示例 - 请不要回答说“为什么你想在第一种情况下这样做”,这真的很令人沮丧。我只是想知道你是否可以将信息传递给stdin
然后提示用户输入。
这个问题没有通用的解决方案。最好的资源似乎是这个邮件列表主题 http://mail.python.org/pipermail/python-list/2000-March/048890.html.
基本上,通过管道连接到程序中stdin
到该管道,而不是到终端。
邮件列表线程有几个相对简单的解决方案 http://mail.python.org/pipermail/python-list/2000-March/020133.html对于*nix:
打开 /dev/tty 替换 sys.stdin:
sys.stdin = open('/dev/tty')
a = raw_input('Prompt: ')
运行脚本时将 stdin 重定向到另一个文件句柄,并从中读取:
sys.stdin = os.fdopen(3)
a = raw_input('Prompt: ')
$ (echo -n test | ./x.py) 3<&0
以及建议使用curses http://mail.python.org/pipermail/python-list/2000-March/055320.html。请注意,邮件列表线程是ancient因此您可能需要修改您选择的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)