# 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