python获取用户输入,管道输入到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

and the contents of 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...

The above will trigger a EOFError: EOF when reading a line error.

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.

The mailing list thread has a couple of relatively simple solutions for *nix:

Open /dev/tty to replace sys.stdin:

sys.stdin = open('/dev/tty')

a = raw_input('Prompt: ')

Redirect stdin to another file handle when you run your script, and read from that:

sys.stdin = os.fdopen(3)

a = raw_input('Prompt: ')

$ (echo -n test | ./x.py) 3

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值