python - 出现错误后如何跳过删除文件?
问题描述
当我运行程序时,我需要创建删除临时文件夹中所有文件的进程,它说“该进程无法访问该文件,因为它正被另一个进程使用。”,所以我试图让它跳过该文件,如果它说,但它不起作用。我对python也很陌生。这是我的代码:
if event in ('Delete Temp'):
while ("temp"):
os.system('cmd /c "del /q/f/s %TEMP%\*"')
if print('The process can not access the file because it is being used by another process.')
pass
解决方案
您可以将删除命令包装在try/except
块中,而不是os
使用模块subprocess
,以便在失败时抛出异常:
from subprocess import run
while condition:
try:
run('cmd /c "del /q/f/s %TEMP%\*"', shell=True, check=True)
except CalledProcessError as ex:
print(f"Failed to delete files. stdout: {ex.stdout}, stderr: {ex.stderr}, returncode: {ex.returncode}")
但是你应该改变你的while条件,你有一个无限循环 - (while "temp"
将永远True
)
推荐阅读
- javascript - 更新 Discord Music Bot 中嵌入的“正在播放”
- netezza - Netezza:更新错误:此类命令不支持跨数据库连接
- javascript - 我被困在这里用 hp bar 解决我的问题
- reactjs - 更改 react-chartjs-3 中的标签位置
- python - 我已将日期作为熊猫数据框的索引。如何搜索特定日期的行?
- c# - Wrap Function / 避免重复 coid
- python - AttributeError:“str”对象没有属性“后代”-BeautifulSoup4
- xml - 删除 xml 标记 notepad++ 但保留文本
- loops - 在 GAMS 中创建宏/循环
- python - 将项目添加到嵌套字典列表中的每个字典