我有一个 python 程序需要几分钟才能完成。我有一些仅在设置变量时打印的调试代码。在我当前的实现中,该变量是通过命令行或环境变量设置的。我想在程序执行时即时启用/禁用调试。
例如,考虑以下代码:
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 (可能在单独的线程中)?
请您参考如下方法:
在使用线程模块进行一些实验后,以下代码对我有用。 监听器线程持续监听标准输入。
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()
