2016-12-15 31 views
0

有什麼辦法讓python腳本將日誌寫入2個不同的位置:文件和終端?但是,如果我手動運行它,它應該只打印日誌到終端。當它被別的東西運行時,它應該只將日誌寫入日誌文件。有沒有可能?python腳本 - 根據運行方式將日誌寫入不同的地方

+0

檢查,如果這可以幫助你 - http://stackoverflow.com/questions/24957734/start-python-script-with-cron-and-output-print對一個文件 – AlokThakur

+0

[檢查Python腳本中的交互式shell]可能的重複(http://stackoverflow.com/questions/6108330/checking-for-interactive-shell-in-a-python-script) – teppic

回答

1

如果程序連接到tty,則可以使用返回True的isatty()方法,否則返回False。所以你的情況,你可以編寫這樣的事:

import sys 

if sys.stdin.isatty(): 
    # Logs put here will be displayed on terminal when you invoke the script via cli 
else: 
    with open("/testFile.txt", "w") as f: 
     f.write('Logging in a file')  
相關問題