我有一个应用程序,当发生条件时,我想在其中覆盖某些功能,例如:
condition_check.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
main.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
。我相信检查库可以用于此目的,但我无法查找示例。
我假设您使用的是Python3。如果您使用的是Python,则只需要设置内置模块的属性即可。
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 *
PEP 8不建议使用通配符导入(),因为通配符导入()不清楚名称空间中存在哪些名称,这会混淆读取器和自动化工具。(几乎是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 2print
是一个语句也是如此。这样做确实有一个缺点,就是要保留print
添加的换行符,但是总可以使用alternate
诸如lambda msg: MsgBox(msg.strip())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句