如何使已打开的文件可读(例如 sys.stdout)? [英] How does one make an already opened file readable (e.g. sys.stdout)?

查看:62
本文介绍了如何使已打开的文件可读(例如 sys.stdout)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在字符串中获取 sys.stdout 的内容.我尝试了显而易见的:

I was trying to get the contents of sys.stdout in a string. I tried the obvious:

def get_stdout():
    import sys

    print('a')
    print('b')
    print('c')

    repr(sys.stdout)

    contents = ""
    #with open('some_file.txt','r') as f:
    #with open(sys.stdout) as f:
    for line in sys.stdout.readlines():
        contents += line
    print(contents)

但这给出了错误:

Exception has occurred: UnsupportedOperation
not readable

那么我该如何更改已打开文件的权限?

So how do I just change the permissions of that already opened file?

我试过了:

    sys.stdout.mode = 'r'

但这仍然会出现相同的错误...

but that still gives the same error...

其他可行的方法是以独立于硬件的方式让我获得 stdout 的名称/路径.

Other things that would work would be to just get me the name/path of stdout in a hardware independent way.

另一件可行的事情是让我在以字符串形式运行主脚本后,将 sys.stdout 的内容放入.

Another thing that would just work is letting me to put the contents of sys.stdout after I've run my main script in a string.

如果您遇到像我这样的错误,这些可能是相关的:为什么 __builtins__既是模块又是字典 Python:__builtin__ 之间有什么区别和 __builtins__?

these might be relevant if you are getting bugs like I am: why __builtins__ is both module and dict Python: What's the difference between __builtin__ and __builtins__?

错误:

line 37, in my_print
    __builtins__["print"](*args, file=f)  # saves to file
TypeError: 'module' object is not subscriptable


我读过的问题没有帮助:


Questions I've read that did not help:

推荐答案

可以使用以下代码:

import sys
from builtins import print as builtin_print
myfile = "output.txt"
def print(*args):
    builtin_print(*args, file=sys.__stdout__)    # prints to terminal
    with open(myfile, "a+") as f:
        builtin_print(*args, file=f)    # saves in a file

这应该重新定义 print 函数,以便它打印到 stdout 和您的文件.然后您可以从文件中读取.

This should redefine the print function so that it prints to stdout and to your file. You can then read from the file.

这篇关于如何使已打开的文件可读(例如 sys.stdout)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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