Warm tip: This article is reproduced from serverfault.com, please click

bash-将输入管道传输到Python程序,然后再从用户那里获取输入

(bash - Pipe input to Python program and later get input from user)

发布于 2011-08-21 21:34:33

假设我想将输入传递给Python程序,然后在命令行上从用户那里获取输入。

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 when reading a line错误。

我还尝试添加sys.stdin.close()一行,提示输入ValueError: I/O operation on closed file

你可以通过管道将信息发送到用户stdin,然后再从用户那里获得输入吗?

注意:这是一个简化的简化示例-请不要回答“为什么要在第一种情况下这样做”,这确实令人沮丧。我只是想知道你是否可以通过管道将信息发送给stdin用户,然后稍后提示用户进行输入。

Questioner
Kevin Burke
Viewed
0
2,905 2013-07-30 22:15:08

对于此问题,没有通用的解决方案。最好的资源似乎是此邮件列表线程

基本上,管道到程序中是将程序的管道连接stdin到该管道,而不是终端。

邮件列表线程为* 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

以及使用诅咒建议请注意,邮件列表线程是古老的,因此你可能需要修改选择的解决方案。