简体   繁体   English

如何从 Python 中的 shell 命令捕获输出?

[英]How can I capture the output from a shell command in Python?

What I need to do is the following: in a Python script spawn, say the ls --colors=always / Linux command, and read its output.我需要做的是:在 Python 脚本 spawn 中,说ls --colors=always / Linux 命令,并读取其输出。 The important part of this is that I need the output to keep all the ANSI escape sequences (colors and such) to later translate these sequences into HTML.重要的部分是我需要输出来保留所有 ANSI 转义序列(颜色等),以便稍后将这些序列转换为 HTML。 I heard that Python pty module can do that, but I could not find a useful example of its usage in the Internet, and this module's documentation is not quite comprehensive.我听说 Python pty模块可以做到这一点,但我在互联网上找不到有用的示例,而且这个模块的文档也不是很全面。 I'll appreciate if someone could guide me through the way of accomplishing this task.如果有人能指导我完成这项任务,我将不胜感激。

import subprocess as sub

process = sub.Popen("ls --colors=always /", stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = process.communicate()

Now all the data you want should be in output - including the ANSI escape sequences.现在你想要的所有数据都应该在output ——包括 ANSI 转义序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM