管道输入到Python程序,后来获得用户输入 [英] Pipe input to Python program and later get input from user
问题描述
比方说,我希望通过管道输入到Python程序,然后再从用户获取输入,在命令行上。
Let's say I want to pipe input to a Python program, and then later get input from the user, on the command line.
echo http://example.com/image.jpg | python solve_captcha.py
和 solve_captcha.py
的内容是:
import sys
image_url = sys.stdin.readline()
# Download and open the captcha...
captcha = raw_input("Solve this captcha:")
# do some processing...
以上将触发引发EOFError:EOF读线的时候
错误
我也试过添加 sys.stdin.close()
线,这促使了 ValueError错误:I / O操作上关闭的文件
。
I also tried adding a sys.stdin.close()
line, which prompted a ValueError: I/O operation on closed file
.
你能管信息标准输入
再后来从用户获取输入?
Can you pipe information to stdin
and then later get input from the user?
注意:这是一个精简,简化的例子 - 请不要说你为什么想这样做,在第一种情况,这是很无奈回应。我只是想知道你能管信息标准输入
键,然后再提示用户输入。
Note: This is a stripped down, simplified example - please don't respond by saying "why do you want to do that in the first case," it's really frustrating. I just want to know whether you can pipe information to stdin
and then later prompt the user for input.
推荐答案
有没有对这个问题的通用解决方案。最好的资源似乎是这个邮件列表线程。
There isn't a general solution to this problem. The best resource seems to be this mailing list thread.
基本上,管道成一个程序连接程序的标准输入
来该管道,而不是终点。
Basically, piping into a program connects the program's stdin
to that pipe, rather than to the terminal.
邮件列表的线程有几个相对简单的解决方案为* nix中:
The mailing list thread has a couple of relatively simple solutions for *nix:
打开/ dev / tty的替换sys.stdin:
sys.stdin = open('/dev/tty')
a = raw_input('Prompt: ')
标准输入重定向到另一个文件句柄当你运行你的脚本,并从阅读:
sys.stdin = os.fdopen(3)
a = raw_input('Prompt: ')
$ (echo -n test | ./x.py) 3<&0
以及建议使用诅咒的。请注意,邮件列表线程的古,所以你可能需要修改你选择的解决方案。
as well as the suggestion to use curses. Note that the mailing list thread is ancient so you may need to modify the solution you pick.
这篇关于管道输入到Python程序,后来获得用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!