gui*_*ooo 8 python windows cmd
如果是这样,我应该研究哪个图书馆(y | ies)?
如果您正在谈论python解释器或CMD.exe,它是您脚本的"父",那么不可能.在每个类似POSIX的系统中(现在你正在运行Windows,看起来可能有一些我不知道的怪癖,YMMV)每个进程都有三个流,标准输入,标准输出和标准错误.Bu默认(在控制台中运行时)会将这些指向控制台,但可以使用管道符号进行重定向:
python script_a.py | python script_b.py
Run Code Online (Sandbox Code Playgroud)
这将脚本a的标准输出流与脚本B的标准输入流联系起来.在此示例中,标准错误仍然发送到控制台.请参阅Wikipedia 上有关标准流的文章.
如果你正在谈论一个子进程,你可以像这样从python启动它(如果你想要双向通信,stdin也是一个选项):
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()
Run Code Online (Sandbox Code Playgroud)
有关管理进程的信息,请参阅Python 子进程模块.对于通信,process.stdin和process.stdout管道被视为标准文件对象.
对于管道使用,从标准输入读取lassevk建议你做这样的事情:
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
Run Code Online (Sandbox Code Playgroud)
sys.stdin和sys.stdout是上面提到的标准文件对象,在sys模块中定义.您可能还想查看管道模块.
使用readline()读取数据就像在我的示例中一样,这是获取数据的一种非常天真的方式.如果输出不是面向行或不确定的,你可能想要查看不幸在Windows中不起作用的轮询,但我确信那里有一些替代方案.
我想我可以为您的问题的第一部分指出一个好的答案。
1.是否可以从Python脚本捕获Python解释器的输出?
答案是“ 是 ”,我个人希望从PEP 343的示例中获得以下内容-“ with”声明文档。
from contextlib import contextmanager
import sys
@contextmanager
def stdout_redirected(new_stdout):
saved_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout.close()
sys.stdout = saved_stdout
Run Code Online (Sandbox Code Playgroud)
像这样使用:
with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
Run Code Online (Sandbox Code Playgroud)
它的一个不错的方面是,它可以仅在脚本执行的一部分而不是整个执行范围内有选择地应用,并且即使在其上下文中引发了未处理的异常时也可以保持有效。如果在首次使用后以追加模式重新打开文件,则可以将结果累积到单个文件中:
with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
print "screen only output again"
with stdout_redirected(open("filename.txt", "a")):
print "Hello world2"
Run Code Online (Sandbox Code Playgroud)
当然,以上内容也可以扩展为也重定向sys.stderr到相同或另一个文件。另请参阅有关相关问题的答案。