2011-06-02 66 views
3

我想從shell(bash)讀取stdin,並將stdout發送到shell以及重定向文件。我嘗試以下:Python - 我如何從shell讀取stdin,並將stdout發送到shell和文件

$ 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打印完成後I型我的輸入,這意味着不能看到提示爲I型。用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 

回答

2
#!/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 
1

看到這個bug,看起來像raw_input將其提示寫入stderr。

http://bugs.python.org/issue1927

+0

我不認爲這是問題。我嘗試了與OP相同的內容,但使用'print'輸出提示,結果相同。 – senderle 2011-06-02 18:54:05

+0

好吧,它只是沒有沖洗你看到相同的症狀 - 請參閱tMCs回答 – rlawson 2011-06-02 19:00:51

+0

你是對的,我現在明白了。 – senderle 2011-06-02 19:01:49