Python子进程获取子进程的outpu

2024-10-01 13:41:25 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicates:
How to get output from subprocess.Popen()
Retrieving the output of subprocess.call()

这是我的问题。我有一个名为device_console的可执行文件。device_控制台为设备提供命令行接口。在设备控制台中,可以运行四个命令: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的子进程,但不知怎么的,我无法将它们组合在一起。你能帮忙吗?在


Tags: 命令localhostoutputdevicestatusexitlistconsole
2条回答

使用^{} module。示例:

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()

听起来你想要更像“期待”的东西。在

退房Pexpect

"Pexpect is a pure Python module that makes Python a better tool for controlling and automating other programs. Pexpect is similar to the Don Libes Expect system, but Pexpect as a different interface that is easier to understand. Pexpect is basically a pattern matching system. It runs programs and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses."

相关问题 更多 >