Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdjhny/6183147 to your computer and use it in GitHub Desktop.
Save mdjhny/6183147 to your computer and use it in GitHub Desktop.
管道和输入同时作为输入的解决办法
如果脚本从管道获取输入,同时需要有输入交互,可以采取以下三种措施:
http://mail.python.org/pipermail/python-list/2000-March/020133.html
* Put the data in a file and pass the name of the file to your
script, then open that file:
lines = open(sys.argv[1]).readlines()
This is probably the nicest solution, and the least prone to making
wierd things happen if your script gets run differently.
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment