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?

2
  • Why are you using a batch file instead of running the Python script directly? Commented Dec 18, 2015 at 0: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 set to either CREATE_NO_WINDOW or DETACHED_PROCESS. Commented Dec 18, 2015 at 0:39

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.