【问题标题】:Python Monkey Patch shutilPython 猴子补丁
【发布时间】:2017-11-13 04:22:37
【问题描述】:

我正在尝试修改 shutil.copyfileobj() 函数,以便将其默认长度从 16*1024 更改为更大的值 (128*1024)。在内部,其他shutil 方法(如move)调用copyfileobj() 函数,我希望这些调用也受到猴子补丁的影响。这似乎不起作用:

import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('test.txt', 'testmove.txt')

我希望这会打印“快速复制文件”,但事实并非如此。有什么方法可以实现我想要做的吗?

【问题讨论】:

  • shutil.move 仅在源和目标路径位于不同文件系统上时执行复制。它们在不同的文件系统上吗?
  • @jwodder,呵呵!谢谢,成功了。

标签: python monkeypatching


【解决方案1】:

我的测试用例坏了。 shutil.move() 仅在源文件和目标文件位于不同设备上时才执行复制。这是一个显示猴子补丁有效的更新版本:

import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('/dev1/test.txt', '/dev2/testmove.txt')

【讨论】:

    猜你喜欢
    • 2012-12-18
    • 2011-04-15
    • 1970-01-01
    • 2017-10-05
    • 2016-09-01
    • 2012-09-16
    • 2020-01-09
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多