2

I have a python program which takes several minutes to finish. I have some debugging code which is printed only when a variable is set. the variable is set through command line or environment variable in my current implementation. I want to enable/disable debugging on the fly when program is executing.

For example, consider following code:

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()

So while the program is executing with debugging off, how can I dynamically enable debugging while the program is executing? In other words, how can I execute function enable_debugging (maybe in a separate thread), when a particular string is inputted?

AMR
  • 25
  • 4

2 Answers2

4

After some experiments using thread module, following code works for me. A listener thread keeps listening to the 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()
AMR
  • 25
  • 4
  • It seems like [threading is recommended over thread](https://stackoverflow.com/questions/5568555/thread-vs-threading) – lucidbrot Nov 14 '19 at 20:05
2

One approach can be to read the value from a file at regular interval.

And update that file when you want debugging on or off.

AMR
  • 25
  • 4