import subprocess
child = subprocess.Popen(['python', 'simple.py'], stdin=subprocess.PIPE)
child.communicate('Alice')
我知道您可以通过沟通与已执行的脚本进行通信 你如何检查一个脚本' simple.py'是要求用户输入?
simple.py可以要求5到10个用户输入,所以简单地硬编码communicate
就不够了。
[编辑]:想要在脚本运行时解析stdout并与脚本进行通信
while True:
if child.get_stdout() == '?':
# send user input
答案 0 :(得分:2)
一个简单的例子:
simple.py:
import subprocess
child = subprocess.Popen(['python2', 'simple.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in iter(child.stdout.readline, ""):
print(line)
if "name" in line:
child.stdin.write("foo\n")
elif "age" in line:
child.stdin.write("100\n")
读写:
what is your name
foo
What is your age
100
输出:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000