redirect prints to log file

前端 未结 8 1398
萌比男神i
萌比男神i 2020-12-02 09:05

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command

相关标签:
8条回答
  • 2020-12-02 10:02

    You can redirect replace sys.stdout with any object which has same interface as sys.stdout, in that object's write you can print to terminal and to file too. e.g. see this recipe http://code.activestate.com/recipes/119404-print-hook/

    0 讨论(0)
  • 2020-12-02 10:07

    You should take a look at python logging module


    EDIT: Sample code:

    import logging
    
    if __name__ == "__main__":
        logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
                            format="%(asctime)-15s %(levelname)-8s %(message)s")
        logging.info("hello")
    

    Produce a file named "logfile" with content:

    2012-10-18 06:40:03,582 INFO     hello
    
    0 讨论(0)
提交回复
热议问题