[英]Python - how can I read stdin from shell, and send stdout to shell and file
I'd like to have a Python script read stdin from the shell (bash), and send stdout to shell as well a redirected file.我想要一个 Python 脚本从 shell (bash) 读取标准输入,并将标准输出发送到 shell 以及重定向文件。 I tried the following:
我尝试了以下方法:
$ cat test.py
#!/usr/bin/python
val = raw_input("enter val: ")
print val
$ ./test.py | tee out
testing
enter val: testing
$ cat out
enter val: testing
For some reason, the raw_input prompt is printed after I type my input, which means I can't see the prompt as I type.出于某种原因,在我输入输入后会打印 raw_input 提示,这意味着我在输入时看不到提示。 With a bash script, I can get something similar to work.
使用 bash 脚本,我可以获得类似的工作。
$ cat test.sh
#!/bin/bash
echo "enter val: "
read val
echo $val
$ ./test.sh | tee out
enter val: testing
testing
$ cat out
enter val: testing
#!/usr/bin/python
import sys
print "enter val: ",
sys.stdout.flush()
val = raw_input()
print val
Or或者
#!/usr/bin/python
import sys
sys.stdout = sys.stderr
val = raw_input("enter val: ")
sys.stdout = sys.__stdout__
print val
See this bug, looks like raw_input writes its prompt to stderr.看到这个错误,看起来 raw_input 将其提示写入标准错误。
http://bugs.python.org/issue1927 http://bugs.python.org/issue1927
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.