How to output to the console and file?

前端 未结 8 1209
青春惊慌失措
青春惊慌失措 2020-11-30 02:54

I\'m trying to find out a way in python to redirect the script execution log to a file as well as stdout in a pythonic way. Is there any easy way of achieving t

8条回答
  •  感动是毒
    2020-11-30 03:30

    Probably the shortest solution:

    def printLog(*args, **kwargs):
        print(*args, **kwargs)
        with open('output.out','a') as file:
            print(*args, **kwargs, file=file)
    
    printLog('hello world')
    

    Writes 'hello world' to sys.stdout and to output.out and works exactly the same way as print().

    Note: Please do not specify the file argument for the printLog function. Calls like printLog('test',file='output2.out') are not supported.

提交回复
热议问题