2017-08-11 126 views
1

我有一個python程序需要幾分鐘才能完成。我有一些調試代碼,只有在設置變量時纔會打印。該變量是通過我當前實現中的命令行或環境變量設置的。我想在程序執行時啓用/禁用調試。如何在程序運行時接受來自stdin的輸入

例如,請考慮下面的代碼:

import time 
import os 
debugging=False 
if "DEBUG" in os.environ: 
    debugging = True 
def debug(): 
    if debugging: 
     print("debug statement"); 
def enable_debugging(): 
    global debugging 
    debugging = True 
def disable_debugging(): 
    global debugging 
    debugging = False 
print("1") 
debug() 
time.sleep(20) 
print("2") 
debug() 

因此,儘管該程序與調試關閉執行中,程序執行時我怎麼能動態地啓用調試?換句話說,當一個特定的字符串被輸入時,如何執行函數enable_debugging(也許在一個單獨的線程中)?

+2

看看[threading module。](https://docs.python.org/3/library/threading.html) –

+1

做了一些實驗並找到了解決辦法。謝謝! –

回答

2

使用線程模塊進行了一些實驗後,以下代碼適用於我。 監聽器線程不斷監聽stdin。

import time 
import os 
import thread 
import sys 
debugging=False 
def check_input(): 
    print("Starting listener thread.") 
    while True: 
     _in = raw_input() 
     print("received input: " + _in) 
     if _in.lower() == "debug": 
     enable_debugging() 
thread.start_new_thread (check_input,()) 

if "DEBUG" in os.environ: 
    debugging = True 
def debug(): 
    if debugging: 
     print("debug statement"); 
def enable_debugging(): 
    global debugging 
    print("enabling debugging") 
    debugging = True 
def disable_debugging(): 
    global debugging 
    debugging = False 
print("1") 
debug() 
time.sleep(20) 
print("2") 
debug() 
2

一種方法可以是定期讀取文件中的值。

並且當你想打開或關閉調試時更新該文件。

相關問題