Shell脚本: Hello.sh
#!/bin/bash
echo "Enter your name: "
read name
echo "Hello $name"
我想从python中调用Hello.sh并以非交互方式填充变量“name”。怎么办呢?
答案 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)
+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