Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

python - How does one make an already opened file readable (e.g. 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)

but that gives the error:

Exception has occurred: UnsupportedOperation
not readable

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

I tried:

    sys.stdout.mode = 'r'

but that still gives the same error...

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


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.


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__?

bug:

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following code:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...