2013-03-21 64 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")