-2

外壳脚本:Hello.sh

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

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

4

2 回答 2

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")
于 2013-03-21T15:20:21.127 回答
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
于 2013-03-21T15:25:35.477 回答