gpt4 book ai didi

python - 将多个命令发送到必须共享环境的 bash shell

转载 作者:行者123 更新时间:2023-11-28 17:47:47 24 4
gpt4 key购买 nike

我试图在这里遵循这个答案:https://stackoverflow.com/a/5087695/343381

我需要在一个环境中执行多个 bash 命令。我的测试用例很简单:

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() 永远不会返回?

注意事项:

  • 在同一环境中从 python 运行多个 bash 命令是绝对必要的。因此,subprocess.communicate() 没有帮助,因为它等待进程终止。
  • 请注意,在我的真实测试用例中,它不是要执行的 bash 命令的静态列表。逻辑更加动态。我无法同时运行所有这些选项。

最佳答案

这里有两个问题:

  1. 您的第一个命令没有产生任何输出。所以第一个读取 block 等待一些。
  2. 您正在使用 read() 而不是 readline() —— read() 将阻塞直到有足够的数据可用。

以下修改后的代码(根据 Martjin 的投票建议更新)工作正常:

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 毫秒的超时 - 根据您的需要进行调整。

关于python - 将多个命令发送到必须共享环境的 bash shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com