TTT
TTT

Reputation: 4434

How to kill a process created by Python subprocess.Popen()

I need to call a DOS .exe file from Python and delete this .exe after the computation. I am able to call it using subprocess.Popen and os.system, however, I could not delete this .exe file if it is called by subprocess.Popen. The error is WindowsError: [Error 5] Access is denied. Can anyone let me know how to kill this process? Thanks!

subprocess approach (does not work):

a = subprocess.Popen("dos.exe", stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(5)
a.kill()
os.remove("dos.exe")

# gets error msg "WindowsError: [Error 5] Access is denied"

os.system approach (works):

a=os.system("dos.exe")
os.remove("dos.exe")

Upvotes: 2

Views: 1186

Answers (1)

spinlok
spinlok

Reputation: 3661

You'll need to wait for the process to complete before deleting the .exe. Call a.communicate() or a.wait() before deleting the .exe

Upvotes: 2

Related Questions