How to redirect 'print' output to a file using python?

后端 未结 11 1063
既然无缘
既然无缘 2020-11-22 17:05

I want to redirect the print to a .txt file using python. I have a \'for\' loop, which will \'print\' the output for each of my .bam file while I want to redirect ALL these

11条回答
  •  忘了有多久
    2020-11-22 17:30

    Don't use print, use logging

    You can change sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using print, use the logging module.

    With logging, you can print just like you would to stdout, or you can also write the output to a file. You can even use the different message levels (critical, error, warning, info, debug) to, for example, only print major issues to the console, but still log minor code actions to a file.

    A simple example

    Import logging, get the logger, and set the processing level:

    import logging
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed
    

    If you want to print to stdout:

    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO) # or any other level
    logger.addHandler(ch)
    

    If you want to also write to a file (if you only want to write to a file skip the last section):

    fh = logging.FileHandler('myLog.log')
    fh.setLevel(logging.DEBUG) # or any level you want
    logger.addHandler(fh)
    

    Then, wherever you would use print use one of the logger methods:

    # print(foo)
    logger.debug(foo)
    
    # print('finishing processing')
    logger.info('finishing processing')
    
    # print('Something may be wrong')
    logger.warning('Something may be wrong')
    
    # print('Something is going really bad')
    logger.error('Something is going really bad')
    

    To learn more about using more advanced logging features, read the excellent logging tutorial in the Python docs.

提交回复
热议问题