使用python以非交互方式输入shell脚本变量值

时间:2013-03-21 15:14:35

标签: python bash shell subprocess stdin

Shell脚本: Hello.sh

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

我想从python中调用Hello.sh并以非交互方式填充变量“name”。怎么办呢?

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:1)

pipes上的

+1。更多的“shell-ish”方法是:

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