如何不将Python管道实例的stdout附加到文件?

2024-06-18 13:10:39 发布

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

在关于pipes的Python手册中,给出了使用f = t.open('pipefile', 'w')的示例,因此来自管道的stdout将转到文件pipefile。我可以这样使用它:

import pipes
import sys
t = pipes.Template()
t.append('tr a-z A-Z', '--')
f = t.open('pipefile', 'w')
sys.stdout = f
print('hello world')

在我执行这个脚本之后,我在文件pipefile中看到“HELLO WORLD”。你知道吗

但我不想将管道的stdout指向文件。我不想管它。因此,当我执行这个脚本时,它会打印HELLO WORLD。你知道吗

我需要改变这两行:

f = t.open('pipefile', 'w')
sys.stdout = f

怎么做?你知道吗


Tags: 文件import脚本示例helloworld管道stdout
1条回答
网友
1楼 · 发布于 2024-06-18 13:10:39

啊哈!似乎模块pipes应该具有与管道相关的功能,但没有该功能—它只能用于将管道重定向到文件,而不能将它们留在stdout。你知道吗

要做我想做的事,我不需要模块pipes,相反,我需要模块os,就像这样

import os, sys
sys.stdout = os.popen('tr a-z A-Z','w',1)
print('hello world')

相关问题 更多 >