简体   繁体   中英

Failed to execute script file (.bat) when running from a python script

I'm trying to make a python script that creates a .txt and a .bat file, which in turn deletes the python script and then itself. However after the script creates the .txt and .bat files it comes up with "Failed to execute script file" error and .bat does not run. What could be wrong?

I'm using pyinstaller to package everything into a single .exe called file.exe . All files are in the same directory.

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

I tried both with cmd.exe to run the .bat and without cmd opening the bat.

Give this a try please. You do not really need to do all the timeouts as this really does run fairly quickly, but I retained them regardless.

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

I would also initiate the script as such for testing purpose.

cmd /c start "" python yourpythonfile.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM