Python subprocess 获取子进程输出

1 投票
2 回答
2348 浏览
提问于 2025-04-15 19:03

可能的重复问题:
如何从subprocess.Popen()获取输出
获取subprocess.call()的输出

我有一个可执行文件,叫做device_console。这个device_console可以让我们通过命令行与设备进行交互。在device_console中,可以运行四个命令:status(状态)、list(列表)、clear(清除)和exit(退出)。每个命令都会产生一些输出。举个例子:

[asdfgf@localhost ~]$ device_console

device_console> list

File A

File B

device_console> status
Status: OK

device_console> clear
All files cleared

device_console> list
device_console> exit

[asdfgf@localhost ~]$

在测试的时候,我想获取每个命令的输出。我想用Python来实现这个功能。我在研究Python的subprocess模块,但总是无法把它们组合在一起。你能帮帮我吗?

2 个回答

2

使用 subprocess 模块。下面是一个例子:

import subprocess

# Open the subprocess
proc = subprocess.open('device_console', stdin=subprocess.PIPE, stdout.subprocess.PIPE)

# Write a command
proc.stdin.write('list\n')

# Read the results back -- this will block until a line of input is received
listing = proc.stdout.readline()

# When you're done, close the input stream so the subprocess knows to exit
proc.stdin.close()

# Wait for subprocess to exit (optional) and get its exit status
exit_status = proc.wait()
2

听起来你想要的东西更像是“Expect”。

可以看看 Pexpect

“Pexpect 是一个纯 Python 模块,它让 Python 更好地控制和自动化其他程序。Pexpect 和 Don Libes 的 Expect 系统类似,但 Pexpect 的界面更容易理解。Pexpect 基本上是一个模式匹配系统。它运行程序并监视输出。当输出符合某个特定模式时,Pexpect 可以像人类一样输入回应。”

撰写回答