Python猴贴舒提

2024-06-16 10:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

我希望这个打印“复制文件快”,但它没有。有什么办法来实现我的尝试吗?你知道吗


Tags: 文件方法函数importtxtmovedeflength
1条回答
网友
1楼 · 发布于 2024-06-16 10:24:36

我的测试用例坏了。shutil.移动()仅在源文件和目标文件位于不同设备上时执行复制。以下是一个更新版本,显示了monkey补丁的工作原理:

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')

相关问题 更多 >