簡體   English   中英

從導入的模塊覆蓋導入模塊的內置函數

[英]Override importing module's built-in functions from imported module

我有一個應用程序,我想在條件發生時覆蓋某些函數,例如:

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.pyprint 我相信檢查庫可以用於此目的,但我無法查找示例。

我假設你使用的是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

不過,我會注意到幾件事:

  1. 由於兩個原因, Flag不是一個好名字: 1 ,它完全沒有描述性。 旗幟僅僅意味着它是True還是False ; 它沒有說明它的用途。 2 ,Python的官方風格指南(PEP 8)推薦使用snake_case,而不是常規變量的PascalCase。 PascalCase應該只用於類。

  2. PEP 8不推薦使用通配符導入( from <module> import * ),因為它們不清楚命名空間中存在哪些名稱,這會使讀取器和自動化工具混淆。 (幾乎是關於進口部分的確切報價。)

  3. 您無需覆蓋print功能。 更好的方法是將sys.stdout覆蓋到控制其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行添加的換行符,但是總是可以使用lambda msg: MsgBox(msg.strip())類的alternate lambda msg: MsgBox(msg.strip())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM