如何从 Python 脚本中捕获 Python 解释器和/或 CMD.EXE 的输出? [英] How to capture Python interpreter's and/or CMD.EXE's output from a Python script?

查看:30
本文介绍了如何从 Python 脚本中捕获 Python 解释器和/或 CMD.EXE 的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 是否可以从 Python 脚本中捕获 Python 解释器的输出?
  2. 是否可以从 Python 脚本中捕获 Windows CMD 的输出?

如果是这样,我应该找哪个图书馆(y|ies)?

If so, which librar(y|ies) should I look into?

推荐答案

如果您谈论的是作为脚本父"的 python 解释器或 CMD.exe,那么不,这是不可能的.在每个类似 POSIX 的系统中(现在您似乎正在运行 Windows,这可能有一些我不知道的怪癖,YMMV)每个进程都有三个流,标准输入、标准输出和标准错误.默认情况下(在控制台中运行时)这些被定向到控制台,但可以使用管道符号重定向:

If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:

python script_a.py | python script_b.py

这将脚本 a 的标准输出流与脚本 B 的标准输入流联系起来.在此示例中,标准错误仍会出现在控制台上.请参阅维基百科上关于标准流的文章.

This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on standard streams on Wikipedia.

如果你在谈论一个子进程,你可以像这样从 python 启动它(如果你想要双向通信,stdin 也是一个选项):

If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):

import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()

有关管理流程的信息,请参阅 Python subprocess 模块.对于通信, process.stdin 和 process.stdout 管道被认为是标准的文件对象.

See the Python subprocess module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard file objects.

对于管道使用,从标准输入读取 lassevk 建议你做这样的事情:

For use with pipes, reading from standard input as lassevk suggested you'd do something like this:

import sys
x = sys.stderr.readline()
y = sys.stdin.readline()

sys.stdin 和 sys.stdout 是如上所述的标准文件对象,在 sys 模块.您可能还想查看 pipes 模块.

sys.stdin and sys.stdout are standard file objects as noted above, defined in the sys module. You might also want to take a look at the pipes module.

虽然在我的示例中使用 readline() 读取数据是一种非常幼稚的获取数据的方式.如果输出不是面向行的或不确定的,您可能需要查看 polling 不幸的是,这在 Windows 中不起作用,但我确信那里有一些替代方案.

Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows, but I'm sure there's some alternative out there.

这篇关于如何从 Python 脚本中捕获 Python 解释器和/或 CMD.EXE 的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆