我有一个应用程序,我想在出现条件时覆盖某些功能,例如:
条件检查.py:
Flag = True
import ctypes # An included library with Python install.
import inspect
def MsgBox(msg):
ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1)
def check():
global print
if Flag:
def print(msg):
MsgBox(msg)
else:
pass
主要.py:
## works
from condition_check import *
MsgBox('this is msgbox')
print('this is a print')
## does not work
import condition_check
condition_check.MsgBox('this is msgbox')
print('this is a print')
我知道
condition_check.py
正在覆盖它自己的 print
而不是 main.py
的 print
。我相信 检查 库可用于此目的,但我无法查找示例。 最佳答案
我假设您使用的是 Python 3。如果是,您只需要设置内置模块的属性。
import builtins
import ctypes
original = builtins.print
Flag = True
def MsgBox(msg):
ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1)
def check():
if Flag:
builtins.print = MsgBox
else:
builtins.print = original
但是,我要注意以下几点:
Flag
不是一个好名字,原因有两个: 1 ,它根本没有描述性。一个标志仅仅意味着它是 True
或 False
;它没有说明它的用途。 2 ,Python 的官方风格指南 (PEP 8) 建议对常规变量使用 snake_case,而不是 PascalCase。 PascalCase 应该只用于类。 from <module> import *
),因为它们使命名空间中存在哪些名称变得不清楚,使读者和自动化工具都感到困惑。 (几乎是 Imports 部分的精确引用。) print
函数。更好的方法是将 sys.stdout
覆盖到控制它去向的流:import ctypes
import sys
def MsgBox(msg):
ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1)
class Printer:
def __init__(self, original, alternate, use_alternate):
self.original = original
self.alternate = alternate
self.use_alternate = use_alternate
def write(self, msg):
if self.use_alternate:
return self.alternate(msg)
return self.original(msg)
sys.stdout = printer = Printer(sys.stdout.write, MsgBox, True)
你的标志就是
printer.use_alternate
。除了更容易控制之外,这也与 Python 2 兼容,即使 Python 2 print
是一个语句。这确实有保留 print
添加的换行符的轻微缺点,但你总是可以使用类似 alternate
lambda msg: MsgBox(msg.strip())
关于python - 从导入的模块覆盖导入模块的内置函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39058351/