2013-03-21 44 views
-2

shell腳本: Hello.sh輸入shell腳本變量的值以非交互方式使用python

#!/bin/bash 
echo "Enter your name: " 
read name 
echo "Hello $name" 

我想從蟒蛇中調用Hello.sh並填寫變量「名」非交互方式。如何做呢?

+0

這是一樣的你[前一個問題(http://stackoverflow.com/questions/15548393/get-shell-script-read-value-從-Python的腳本)。 – chepner 2013-03-21 15:26:55

回答

1

+1的pipes。一個更「殼十歲上下」的方法是:

import subprocess 

the_name = 'the_name' 
myproc = subprocess.Popen(['echo %s | bash Hello.sh' % the_name], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell=True) 
out, err = myproc.communicate() 

print out 
+0

'shell = True',我認爲最好傳遞一個字符串,而不是一個列表。 – mgilson 2013-03-21 15:26:19

+0

@ shell = True時@mgilson:_If args是一個字符串,該字符串指定要通過shell執行的命令。如果args是一個序列,則第一個項目指定命令字符串,並且任何附加項目都將被視爲shell本身的附加參數。因此,這並不重要。 – dmg 2013-03-21 15:30:09

+0

感謝它以我想要的方式工作。 – 2013-03-21 15:30:57

3

你應該能夠Popen.communicate與子:

from subprocess import Popen,PIPE 
p = Popen(['bash','./Hello.sh'],stdin=PIPE,stderr=PIPE,stdout=PIPE) 
stdout_data,stderr_data = p.communicate("Hello World!\n")