Subprocess.run – Kill process in Python
Question:
In python I need to use Subprocess like that:
subprocess.run(cmd, text=True,shell=True,cwd=self.cwd,stderr=subprocess.STDOUT,stdout=subprocess.PIPE)
Unfortunatelly the process sometimes gets stuck. So I need to check the timeout manually ( via threading… ) I know there is some option with .Popen
, but there the timeout is not reliable and the process gets stuck also.
My question: If the Subprocess.run(...)
gets stuck, how to terminate (kill) it? There is bunch of hint when using .Popen
, but I could not find any with .run
Thank you in advance.
Answers:
Solution:
Instead of using subprocess.run(...)
I used subprocess.check_output
(I wanted to have it like a blocking function until the subprocess finishs or the timeout occures).
I already found out that for my (and many others application) is better to set shell=False
!
Now with all these configuration, the timeout in subprocess works reliably!
Also I added param. creationflags=CREATE_NO_WINDOW
which causes to not opening an empty shell window when calling subprocess in my .exe version of my app (using cx_Freeze).
In python I need to use Subprocess like that:
subprocess.run(cmd, text=True,shell=True,cwd=self.cwd,stderr=subprocess.STDOUT,stdout=subprocess.PIPE)
Unfortunatelly the process sometimes gets stuck. So I need to check the timeout manually ( via threading… ) I know there is some option with .Popen
, but there the timeout is not reliable and the process gets stuck also.
My question: If the Subprocess.run(...)
gets stuck, how to terminate (kill) it? There is bunch of hint when using .Popen
, but I could not find any with .run
Thank you in advance.
Solution:
Instead of using subprocess.run(...)
I used subprocess.check_output
(I wanted to have it like a blocking function until the subprocess finishs or the timeout occures).
I already found out that for my (and many others application) is better to set shell=False
!
Now with all these configuration, the timeout in subprocess works reliably!
Also I added param. creationflags=CREATE_NO_WINDOW
which causes to not opening an empty shell window when calling subprocess in my .exe version of my app (using cx_Freeze).