在 Python 中与另一个命令行程序交互

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1020980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:17:11  来源:igfitidea点击:

Interacting with another command line program in Python

pythoncommand-linesubprocess

提问by

I need to write a Python script that can run another command line program and interact with it's stdin and stdout streams. Essentially, the Python script will read from the target command line program, intelligently respond by writing to its stdin, and then read the results from the program again. (It would do this repeatedly.)

我需要编写一个 Python 脚本,它可以运行另一个命令行程序并与它的 stdin 和 stdout 流交互。本质上,Python 脚本将从目标命令行程序读取,通过写入其标准输入来智能响应,然后再次从程序读取结果。(它会反复这样做。)

I've looked through the subprocess module, and I can't seem to get it to do this read/write/read/write thing that I'm looking for. Is there something else I should be trying?

我已经查看了 subprocess 模块,但似乎无法让它执行我正在寻找的读/写/读/写操作。还有什么我应该尝试的吗?

回答by Alex Martelli

To perform such detailed interaction (when, outside of your control, the other program may be buffering its output unless it thinks it's talking to a terminal) needs something like pexpect-- which in turns requires pty, a Python standard library module that (on operating systems that allow it, such as Linux and Mac OS x) implements "pseudo-terminals".

要执行如此详细的交互(当在您的控制之外,另一个程序可能正在缓冲其输出,除非它认为它正在与终端交谈)需要类似pexpect 的东西——这反过来又需要pty一个 Python 标准库模块(在操作时)允许它的系统,例如 Linux 和 Mac OS x) 实现了“伪终端”。

Life is harder on Windows, but maybe this zipfilecan help -- it's supposed to be a port of pexpectto Windows (sorry, I have no Windows machine to check it on). The project in question, called wexpect, lives here.

Windows 上的生活更难,但也许这个 zipfile可以帮助 - 它应该是pexpectWindows的端口(抱歉,我没有 Windows 机器可以检查它)。有问题的项目,称为wexpect,住在这里

回答by Anurag Uniyal

see the question wxPython: how to create a bash shell window?

看到问题 wxPython: how to create a bash shell window?

there I have given a full fledged interaction with bash shell reading stdout and stderr and communicating via stdin

在那里,我已经与 bash shell 读取 stdout 和 stderr 并通过 stdin 进行了完整的交互

main part is extension of this code

主要部分是此代码的扩展

bp = Popen('bash', shell=False, stdout=PIPE, stdin=PIPE, stderr=PIPE)
bp.stdin.write("ls\n")
bp.stdout.readline()

if we read all data it will get blocked so the link to script I have given does it in a thread. That is a complete wxpython app mimicking bash shell partially.

如果我们读取所有数据,它将被阻止,因此我提供的脚本链接在一个线程中执行。这是一个完整的 wxpython 应用程序,它部分模仿了 bash shell。