How to output to the console and file?

前端 未结 8 1210
青春惊慌失措
青春惊慌失措 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:36

    Create an output file and custom function:

    outputFile = open('outputfile.log', 'w')
    
    def printing(text):
        print(text)
        if outputFile:
            outputFile.write(str(text))
    

    Then instead of print(text) in your code, call printing function.

    printing("START")
    printing(datetime.datetime.now())
    printing("COMPLETE")
    printing(datetime.datetime.now())
    

提交回复
热议问题