本文介绍了发送多个命令是bash shell必须共享环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在这里遵循这样的回答:
I am attempting to follow this answer here: http://stackoverflow.com/a/5087695/343381
我需要一个单一的环境中执行多个命令的bash。我的测试案例很简单:
I have a need to execute multiple bash commands within a single environment. My test case is simple:
import subprocess
cmd = subprocess.Popen(['bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Write the first command
command = "export greeting=hello\n"
cmd.stdin.write(command)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
result = cmd.stdout.read()
print result
# Write the second command
command = "echo $greeting world\n"
cmd.stdin.write(command)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
result = cmd.stdout.read()
print result
我预计(基于参考答案)发生的是,我看到Hello World字样。实际发生的事情是,它挂在第一个 cmd.stdout.read()
,永不返回。
任何人都可以解释为什么 cmd.stdout.read()
永远不会返回?
Can anyone explain why cmd.stdout.read()
never returns?
注:
- 这是绝对必要的,我运行蟒蛇在同一环境中的多个的bash命令。因此,subprocess.communicate()没有帮助,因为它等待进程终止。
- 请注意,在我的实际测试的情况下,它不是庆典的静态列表命令来执行。其中的逻辑是更有活力。我没有运行所有的人都在一次的选择。
推荐答案
您有两个问题在这里:
- 您的第一个命令不产生任何输出。因此,第一个读块等待一些。
- 您正在使用,而不是读的ReadLine()() - 阅读()将阻塞,直到足够的数据可用
以下修改code(带Martjin的投票建议更新)正常工作:
The following modified code (updated with Martjin's polling suggestion) works fine:
import subprocess
import select
cmd = subprocess.Popen(['bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
poll = select.poll()
poll.register(cmd.stdout.fileno(),select.POLLIN)
# Write the first command
command = "export greeting=hello\n"
cmd.stdin.write(command)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
ready = poll.poll(500)
if ready:
result = cmd.stdout.readline()
print result
# Write the second command
command = "echo $greeting world\n"
cmd.stdin.write(command)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
ready = poll.poll(500)
if ready:
result = cmd.stdout.readline()
print result
上面有一个500毫秒超时 - 调整您的需求。
The above has a 500ms timeout - adjust to your needs.
这篇关于发送多个命令是bash shell必须共享环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!