【问题标题】:How to accept input from stdin in background while program is running程序运行时如何在后台接受来自标准输入的输入
【发布时间】:2017-08-13 21:33:58
【问题描述】:

我有一个 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(可能在单独的线程中)?

【问题讨论】:

标签: python


【解决方案1】:

在使用线程模块进行一些实验后,以下代码对我有用。 侦听器线程一直在侦听标准输入。

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】:

一种方法是定期从文件中读取值。

并在您想要打开或关闭调试时更新该文件。

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2012-07-05
    相关资源
    最近更新 更多