2017-08-11 124 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

一种方法可以是定期读取文件中的值。

并且当你想打开或关闭调试时更新该文件。

相关问题