1. 程式人生 > >python內置函數print輸出到文件,實現日誌記錄的功能

python內置函數print輸出到文件,實現日誌記錄的功能

imp inpu 函數 rgs print top args txt war

# bulid time 2018-6-22
import os
import time

def log(*args, **kwargs):  # *kargs 為了通用 可不傳
    rule = "%Y/%m/%d  %H:%M:%S"  # 定義格式
    value = time.localtime(int(time.time()))  # 轉換時間
    dt = time.strftime(rule, value)   #  根據規則轉換時間
    with open("./log", "a") as f:   # 打開文件  把print函數輸出的數據寫入到文件    
        print(dt, *args, file=f, **kwargs)

def main():
	while True:
	    a = input("請輸入:")
	    if a == "q":
	        log(__file__)
	        log(os.path.dirname("/home/kali/Desktop/log.py"))  # 沒有數據
	        log(os.path.abspath(os.path.dirname(__file__))) # 拿到當前路徑
	        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內置函數的file參數,可以實現把輸出寫入文件,而不再終端顯示, 看了看看print的文檔介紹, 寫了一個小demo, 順便還了解了一下os.path.* , 以及時間模塊,不錯不錯!

功能說明: 獲取輸入內容, 寫入文件, 輸入"q",退出. 可以作為一個記錄日誌的小腳本

在當前目錄生成logt.txt 文件

效果如下:

2018/07/18 18:36:46 hello world!
2018/07/18 18:37:00 life is 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內置函數print輸出到文件,實現日誌記錄的功能