我正在尝试创建一个Python脚本,该脚本创建一个.txt
和一个.bat
文件,依次删除该python脚本和其自身。但是,脚本创建了.txt
和.bat
文件后,它会出现"Failed to execute script file"
错误,并且.bat
无法运行。怎么了?
我正在使用pyinstaller
将所有内容打包到一个称为.exe
的单个file.exe
中。所有文件都在同一目录中。
import subprocess
import time
###--- Create .txt ---###
text = "hello"
f = open("document.txt", 'a+')
f.write(text)
f.close()
###--- Create .bat ---###
myBat = open('C:\\Users\\Me\\Desktop\\destruction.bat','w+')
myBat.write('SLEEP 5 \n') # Wait to make sure file.exe is terminated before continuing
myBat.write('DEL "C:\\Users\\Me\\Desktop\\file.exe" \n')
myBat.write('DEL "%~f0" \n')
myBat.close()
time.sleep(10) # Wait to make sure everything is completed
###--- Run destruction.bat and exit ---###
subprocess.Popen(['cmd.exe','/c',r'C:\Users\Me\Desktop\destruction.bat'], stdin=None, stdout=None, stderr=None, close_fds=True)
exit()
我尝试使用cmd.exe来运行.bat,而没有使用cmd来打开蝙蝠。
答案 0 :(得分:0)
请尝试一下。您真的不需要做所有的超时,因为它确实可以很快地运行,但是无论如何我都保留了它们。
import subprocess
import time
###--- Create .txt ---###
text = "hello"
f = open("document.txt", 'a+')
f.write(text)
f.close()
###--- Create .bat ---###
myBat = open('C:\\Users\\Me\\Desktop\\destruction.bat','w+')
myBat.write('timeout /t 1 \n') # Wait to make sure file.exe is terminated before continuing
myBat.write('(del /q "C:\\Users\\Me\\Desktop\\file.exe" "%~f0")>nul >2^&1 & exit\n')
myBat.close()
time.sleep(3) # Wait to make sure everything is completed
###--- Run destruction.bat and exit ---###
subprocess.Popen([C:\Users\Me\Desktop\destruction.bat'])
exit()
出于测试目的,我还将启动脚本。
cmd /c start "" python yourpythonfile.py