2

I have a batch file which run a python based application which reads a messages continuously. I have python script which closes the application after a timeout period and Execute the Remaining code.

I am using Subprocess.Popen for Batch file run and terminate() call to terminate but the Cmd Window is still in OPen. It is not closing?

And the code is not executing untill the Window Closes. How can i forcly close the cmd?

Vanarajan
  • 973
  • 1
  • 10
  • 35
  • Why are you using a batch file instead of running the Python script directly? – Eryk Sun Dec 18 '15 at 00:36
  • It's not a "cmd" window. It's a console window hosted by conhost.exe. It won't close until all attached processes have exited. You're killing cmd.exe, but the child python.exe process is also attached to the console. Do you even need the console window? Try running the child process [with `creationflag`](http://stackoverflow.com/a/7006424) set to either `CREATE_NO_WINDOW` or `DETACHED_PROCESS`. – Eryk Sun Dec 18 '15 at 00:39

1 Answers1

1

You can use psutil

And specifically the Process.terminate() function.

lets say your command prompt window name is "myscript"

for proc in psutil.process_iter():
    if proc.name() == "myscript":
        proc.terminate()

Or you can run another command, for instance taskkill

taskkill /F /T /IM myscript
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • I am using this code for killing the Process: `def kill(proc_pid): process = psutil.Process(proc_pid) for proc in process.get_children(recursive=True): proc.kill() process.kill() ` – chandra kanth Chandra Dec 15 '15 at 09:02
  • And? It should work if you can get the correct pid. Note that if you set the shell argument to True, this is the process ID of the spawned shell. You should do a little research into how this works. Or you could use psutil to spawn the process, and to kill it as well. – Inbar Rose Dec 15 '15 at 13:48