Python 如何在文件和终端之间切换sys.stdout?
我知道,如果您想将stdout重定向到一个文件,您可以这样做Python 如何在文件和终端之间切换sys.stdout?,python,linux,stdout,Python,Linux,Stdout,我知道,如果您想将stdout重定向到一个文件,您可以这样做 sys.stdout = open(fpath, 'w') holder = sys.stdout sys.stdout = open(fpath, 'w') print('write something to file') sys.stdout = holder print('write something to console') 但是我怎样才能切换回stdout在终端上写入呢?更好的选择是在需要时直接写入文件 with op
sys.stdout = open(fpath, 'w')
holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')
但是我怎样才能切换回stdout在终端上写入呢?更好的选择是在需要时直接写入文件
with open('samplefile.txt', 'w') as sample:
print('write to sample file', file=sample)
print('write to console')
重新分配stdout意味着您需要跟踪以前的文件描述符,并在希望向控制台发送文本时将其分配回
如果你真的必须重新分配,你可以这样做
sys.stdout = open(fpath, 'w')
holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')
您可以将其分配给变量,然后再重新分配
temp = sys.stdout
print('console')
sys.stdout = open('output.txt', 'w')
print('file')
sys.stdout = temp
print('console')
您还可以找到如何将其与上下文管理器一起使用的示例,以便您可以使用with
import sys
from contextlib import contextmanager
@contextmanager
def custom_redirection(fileobj):
old = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = old
# ---
print('console')
with open('output.txt', 'w') as out:
with custom_redirection(out):
print('file')
print('console')
代码来源:
目前,您甚至可以在contextlib
import sys
from contextlib import redirect_stdout
print('console')
with open('output.txt', 'w') as out:
with redirect_stdout(out):
print('file')
print('console')
顺便说一句:如果要将所有文本重定向到文件,则可以使用system/shell进行此操作
$ python script.py > output.txt
首先是
temp=sys.stdout
,然后是sys.stdout=temp
你在末尾写sys.stdout=sys.\uuuuuuuuuuuuuuu
(),所以我认为你的问题是重复的,这回答了你的问题吗?这通常是首选的解决方案,但在某些情况下,人们确实希望重定向stdout,而现在只需要contextlib.redirect\u stdout
。