简体   繁体   English

从 python 脚本运行时无法执行脚本文件 (.bat)

[英]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.我正在尝试制作一个 python 脚本,它创建一个.txt和一个.bat文件,这反过来又删除了 python 脚本,然后它本身。 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.但是,在脚本创建.txt.bat文件后,它会出现"Failed to execute script file"错误并且.bat无法运行。 What could be wrong?可能有什么问题?

I'm using pyinstaller to package everything into a single .exe called file.exe .我正在使用pyinstaller将所有内容打包到一个名为file.exe .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.我尝试使用 cmd.exe 来运行 .bat 并且不使用 cmd 打开 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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