Python-如何从Shell读取stdin并将stdout发送到shell和文件 [英] Python - how can I read stdin from shell, and send stdout to shell and file
本文介绍了Python-如何从Shell读取stdin并将stdout发送到shell和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让一个Python脚本从shell(bash)读取stdin,然后将stdout以及重定向文件发送到shell.我尝试了以下方法:
I'd like to have a Python script read stdin from the shell (bash), and send stdout to shell as well a redirected file. 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
由于某种原因,在键入输入后会显示raw_input提示符,这意味着我在键入时看不到该提示符.使用bash脚本,我可以获得与工作类似的东西.
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. With a bash script, I can get something similar to work.
$ 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
或
#!/usr/bin/python
import sys
sys.stdout = sys.stderr
val = raw_input("enter val: ")
sys.stdout = sys.__stdout__
print val
这篇关于Python-如何从Shell读取stdin并将stdout发送到shell和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文