【问题标题】:How to toggle sys.stdout between a file and terminal?如何在文件和终端之间切换 sys.stdout?
【发布时间】:2019-12-09 19:58:14
【问题描述】:

我知道如果你想将标准输出重定向到一个文件,你可以简单地这样做。

sys.stdout = open(fpath, 'w')

但是如何切换回标准输出以在终端上写入?

【问题讨论】:

标签: python linux stdout


【解决方案1】:

您可以将其分配给变量,然后再将其分配回

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')

代码来自:Python 101: Redirecting stdout

目前你甚至可以在contextlib中找到redirect_stdout

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

【讨论】:

  • 这几天只是contextlib.redirect_stdout
【解决方案2】:

更好的选择是在需要时直接写入文件。

with open('samplefile.txt', 'w') as sample:
    print('write to sample file', file=sample)

print('write to console')

重新分配标准输出意味着您需要跟踪以前的文件描述符,并在您想向控制台发送文本时将其重新分配。

如果你真的必须重新分配,你可以这样做。

holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')

【讨论】:

  • 这通常是首选的解决方案,但在某些情况下,人们真的想重定向标准输出而不是其他任何东西(例如,因为想调用使用打印的现有代码)
猜你喜欢
  • 1970-01-01
  • 2018-07-04
  • 2022-01-23
  • 2010-12-19
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
相关资源
最近更新 更多