如何修复“selfdeleting.exe”的早期删除?

2024-03-29 05:53:34 发布

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

为了测试和个人的概念证明,我有一个.exe文件,它只输出一个简单的字符串,然后调用系统停顿(字面上的^ {< CD1>}在C++中)。在

我有一个简单的Python脚本,我正在一个Windows XP虚拟机上测试,当出现问题时,它会执行以下操作:

subprocess.call(r'echo Nothing special. > c:\blank.txt', shell=True)
subprocess.call(r'type pause.exe > c:\blank.txt:ads.exe', shell=True)
subprocess.call(r'start c:\blank.txt:ads.exe', shell=True)
subprocess.call(r'del c:\blank.txt', shell=True)

显然,这些命令在命令行上都能很好地工作,为什么它们在通过Python调用时不能正常工作呢?在

我收到以下弹出错误消息:

blank.txt:ads.exe has encountered a problem and needs to close. We are sorry for the inconvenience.

If you were in the middle of something, the information you were working on might be lost.

文件确实也被删除了。似乎系统暂停被delete命令压碎了,当我希望.exe弹出时,等我按enter键,然后脚本将继续并删除文件。在


Tags: 文件the命令txt脚本youtrue系统
3条回答

结果是每个subprocess.call(..., shell=True)都会立即返回,因为它们只是告诉shell执行一个命令。在命令行上,调用一个使用start命令运行的exe仍将立即返回,即使exe尚未终止。start立即返回,需要通知它等待:

subprocess.call(r'echo Nothing special. > c:\blank.txt', shell=True)
subprocess.call(r'type pause.exe > c:\blank.txt:ads.exe', shell=True)
subprocess.call(r'start /wait c:\blank.txt:ads.exe', shell=True)
subprocess.call(r'del c:\blank.txt', shell=True)

windows shell start命令将在新的shell中启动程序,然后继续。要等待它完成,请使用call

subprocess.call(r'call c:\blank.txt:ads.exe', shell=True)

考虑到这些症状,我的理解是,只有在这个可执行文件完成初始化后,您才能安全地删除此特定设置下的可执行文件(Windows XP,可能是在特定的修补程序级别,当可执行文件来自备用流时)。如果在加载可执行文件时删除它,程序将崩溃。在

在提示符处键入这些命令时,在运行start c:\blank.txt:ads.exedel c:\blank.txt之间会有一段时间,给程序足够的时间来完成加载。当您从脚本运行它们时,两者之间的间隔要短得多(start从一个新进程分支,新程序的初始化是异步进行的)。初始化和删除之间存在竞争条件;哪一个获胜取决于执行删除的速度。在

请尝试在删除文件之前尝试延迟:

import subprocess, time
subprocess.call(r'echo Nothing special. > c:\blank.txt', shell=True)
subprocess.call(r'type pause.exe > c:\blank.txt:ads.exe', shell=True)
subprocess.call(r'start c:\blank.txt:ads.exe', shell=True)
time.sleep(42)  # 42 seconds is overkill, but the delay isn't predictable
subprocess.call(r'del c:\blank.txt', shell=True)

相关问题 更多 >