Jason
Jason

Reputation: 31

subprocess.popen pid change

I have a script in which I use subprocess.Popen to start an external program and process.kill() to kill it pretty much as soon as it's started. I've been getting Windows Error [5] (Access Denied) every time the script tries to kill it. I've realized that the pid of the program is actually changing after it's opened. Is there a way, in Python, to monitor the process for the change, or to just retrieve the new pid?

Here is the code:

import subprocess
import time

proc  =  subprocess.Popen(Path/to/WinSCP.exe)
time.sleep(2)
proc.kill()

The error:

Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Path", line 231, in __call__
self.scpsetup()
File "C:\Path", line 329, in scpsetup
proc.kill()
File "C:\Python27\lib\subprocess.py", line 1019, in terminate
_subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied

Upvotes: 1

Views: 1639

Answers (1)

Jason
Jason

Reputation: 31

This is what I ended up doing;

import tempfile
import subprocess
import time

# Create a temp file to receive output
tf      =  tempfile.NamedTemporaryFile(delete=False)
output  =  open(tf.name, "w")

# Open and close WinSCP
subprocess.Popen(Path/To/WinSCP.exe)
time.sleep(2)
subprocess.call("TASKKILL /IM WinSCP.exe", stdout=output)
tf.close()

The issue I had with methods like this before was that I couldn't hide the output of the command. This may not be the prettiest way to accomplish this but it works.

Also note that I am using Windows 8. I understand that the command itself may vary slightly in different versions of Windows.

Upvotes: 2

Related Questions