外壳脚本:Hello.sh
#!/bin/bash
echo "Enter your name: "
read name
echo "Hello $name"
我想从 python 中调用 Hello.sh 并以非交互方式填充变量“name”。怎么做到呢?
外壳脚本:Hello.sh
#!/bin/bash
echo "Enter your name: "
read name
echo "Hello $name"
我想从 python 中调用 Hello.sh 并以非交互方式填充变量“name”。怎么做到呢?
您应该能够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 在管道上。一个更“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