如何使已打开的文件可读(例如sys.stdout)?
我试图获取sys.stdout
字符串中的内容。我尝试了明显的方法:
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
那么,如何更改已打开文件的权限?
我试过了:
sys.stdout.mode = 'r'
但这仍然会产生相同的错误…
其他可行的stdout
方法是以硬件独立的方式获取名称/路径。
可以正常工作的另一件事是让我sys.stdout
在字符串中运行主脚本后将内容放入。
如果您遇到像我这样的错误,这些可能是相关的:为什么__builtins__既是模块又是字典
python:__builtin__和__builtins__有什么区别?
错误:
line 37, in my_print
__builtins__["print"](*args, file=f) # saves to file
TypeError: 'module' object is not subscriptable
我读过的问题没有帮助: