2013-02-19 120 views
-2

我正在嘗試編寫一個shell腳本,它將運行一個採用某些原始輸入的python文件。 python腳本基本上是:從shell輸入一個python腳本?

def main(): 
    name=raw_input("What's your name?") 
    print "Hello, "+name 
main() 

我想讓shell腳本運行腳本並自動將輸入提供給它。我已經看到很多方法來從python函數返回的shell輸入,或者如何通過輸入運行python運行shell,但是沒有這種方式。基本上,我只是想的東西做:

python hello.py 
# give the python script some input here 
# then continue on with the shell script. 
+2

'回聲 「看這個!」 | python hello.py' - 我們在談論什麼shell? – moooeeeep 2013-02-19 19:05:38

+0

看起來像UUOE(與[UUOC](http://partmaps.org/era/unix/award.html)密切相關) – mgilson 2013-02-19 19:07:06

+0

也看看[這個答案](http://stackoverflow.com/ a/6271995/1025391)關於Python中的自動化測試和stdin輸入。 – moooeeeep 2013-02-19 19:20:25

回答

4

你的意思是這樣的:

python hello.py <<EOF 
Matt 
EOF 

這就是所謂的bash HERE document

+0

是的,這是完美的,謝謝 – 2013-02-19 19:08:19

0

確實沒有比sys.stdin更好的方式給出原始輸入。它也是跨平臺的。

import sys 
print "Hello {0}!".format(sys.stdin.read()) 

然後

echo "John" | python hello.py # From the shell 
python hello.py < john.txt # From a file, maybe containing "John" 
+0

第二個是貓的無用的...'python hello.py mgilson 2013-02-19 19:09:30

+0

@mgilson確實......老習慣很難死。 – 2013-02-19 19:10:37

+0

我仍然這麼做(很常見)。 – mgilson 2013-02-19 19:11:47

相關問題