在我的模拟中,Python创建了名为__pycache__的文件夹。不止一个,还有很多。__pycache__-folders几乎总是在执行的模块旁边创建的。
但是这些模块分散在我的目录中。主文件夹名为LPG,有许多子文件夹,而这些子文件夹又有更多的子文件夹。__pycache__-folders可以发生在所有可能的地方。
在我的模拟结束时,我想清理和删除LPG-tree中所有名为-tree的文件夹。
做这件事最好的方法是什么?
目前,我正在调用下面的功能在模拟结束(也在模拟启动)。但是,这有点烦人,因为我必须特别写下可能发生__pycache__-folder的每一条路径。
def clearCache():
"""
Removes generic `__pycache__` .
The `__pycache__` files are automatically created by python during the simulation.
This function removes the generic files on simulation start and simulation end.
"""
try:
shutil.rmtree(Path(f"{PATH_to_folder_X}/__pycache__"))
except:
pass
try:
shutil.rmtree(Path(f"{PATH_to_folder_Y}/__pycache__"))
except:
pass发布于 2020-09-02 20:33:58
下面是简单的解决方案,如果您已经知道__pycache__文件夹的位置,只需尝试以下方法
import shutil
import os
def clearCache():
"""
Removes generic `__pycache__` .
The `__pycache__` files are automatically created by python during the simulation.
This function removes the genric files on simulation start and simulation end.
"""
path = 'C:/Users/Yours/Desktop/LPG'
try:
for all in os.listdir(path):
if os.path.isdir(path + all):
if all == '__pycache__':
shutil.rmtree(path + all, ignore_errors=False)
except:
pass
clearCache()简单地说,您仍然可以修改路径到实际您的路径。如果您希望脚本渗透到子目录中以删除pycache文件夹,只需检查以下内容
示例
import shutil
import os
path = 'C:/Users/Yours/Desktop/LPG'
for directories, subfolder, files in os.walk(path):
if os.path.isdir(directories):
if directories[::-1][:11][::-1] == '__pycache__':
shutil.rmtree(directories)发布于 2021-01-25 12:26:41
这将递归地删除当前目录中的所有*.pyc文件和pycache目录:
import os
os.popen('find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf')find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf发布于 2020-09-02 20:37:26
这里是一个框架挑战:如果您不希望字节码缓存,最好的解决方案是首先不生成它们。如果您总是在每次运行后删除它们,那么它们比无用的还要糟糕。以下任一项:
-B选项调用python/python3 (影响单个启动),或.PYTHONDONTWRITEBYTECODE环境变量设置为影响所有启动,直到未设置为止,例如在bash中这确实需要在Python启动之前进行设置,因此,也许可以用一个简单的bash脚本来包装您的脚本,这些脚本用适当的开关/环境来调用真正的Python。
https://stackoverflow.com/questions/63712737
复制相似问题