Pipe input to Python program and later get input from user

后端 未结 5 921
借酒劲吻你
借酒劲吻你 2020-12-13 10:53

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          


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-13 11:14

    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<&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.

提交回复
热议问题