Python built-in function print output to file for logging functions

Source: Internet
Author: User

# bulid time 2018-6-22import osimport timedef log (*args, **kwargs):  # *kargs do not pass    rule = "%y/%m/%d  %h:%m:% for general purposes" S "  # definition Format    value = time.localtime (int (time.time ()))  # conversion time    dt = time.strftime (rule, value)   #  According to the rule conversion time with    open ("./log", "a") as F:   # Open File  writes the output data of the print function to the file            print (dt, *args, File=f, **kwargs) def main (): while True:    a = input ("Please enter:")    if a = = "Q":        log (__file__)        log (Os.path.dirname ("/home/ kali/desktop/log.py ")  # No data        log (Os.path.abspath (Os.path.dirname (__file__)) # Get the current path        log (__name_ _) # __name__        log (Os.path.abspath (__file__)) #当前文件绝对路径        log (Os.path.dirname (Os.path.dirname ( Os.path.abspath (__file__)))          log (os.path.join) break    log (a) if __name__ = = "__main__": Main ()
Python built-in function of the file parameter, you can implement the output to write files, and no longer terminal display, looked at the print document introduction, wrote a small demo, by the way also learned about os.path.*, and the time module, good good!

Function Description: Get input, write to file, enter "Q", exit. A small script that can be used as a logging

Generate the Logt.txt file in the current directory

The effect is as follows:

2018/07/18 18:36:46 Hello world!
2018/07/18 18:37:00 life are short, you need python!
2018/07/18 18:37:02 log.py
2018/07/18 18:37:02/home/kali/desktop
2018/07/18 18:37:02/home/kali/desktop
2018/07/18 18:37:02 __main__
2018/07/18 18:37:02/home/kali/desktop/log.py
2018/07/18 18:37:02/home/kali
2018/07/18 18:37:02 <function Join at 0x7f1c5c206268>

Python built-in function print output to file for logging functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.