How to kill a subprocess in python - python

I have code which runs a webcamera on a linux pc using the gst-launchcommand.
When I kill the process, the webcamera window does not turn off, but the program stops running. I want the webcamera window also to be closed.
Can you help me on this?
import subprocess
import time
import os
import signal
cmd = "gst-launch-1.0 -v v4l2src ! video/x-raw,format=YUY2 ! videoconvert ! autovideosink"
process = subprocess.Popen(cmd, shell = True)
time.sleep(5)
#print(subprocess.Popen.pid)
#process.terminate()
os.kill(process.pid, signal.SIGKILL)
#process.kill()

Hope it will help you.
import os
import signal
import subprocess
process = subprocess.Popen(cmd, shell = True)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)

For me, the currently accepted answer will terminate the main program as well. If you experience the same problem and want it to continue, you will have to also add the argument preexec_fn=os.setsid to popen. So in total:
import os
import signal
import subprocess
process = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
I got this from here: https://stackoverflow.com/a/4791612/11642492

Related

kill process do not kill the subprocess and do not close a terminal window

I am working on UBUNTU and I have file main.py with a code inside:
#!/usr/bin/env python3
# coding=utf-8
import os
import time
from subprocess import Popen, PIPE, call, signal
base_path = os.path.abspath('')
path_to_file = base_path + '/test_subprocess.py'
p = Popen(['gnome-terminal', "--", path_to_file])
time.sleep(2)
os.kill(p.pid, signal.SIGKILL)
I have test_subprocess.py with code like that:
#!/usr/bin/env python3
# coding=utf-8
import time
def print_message():
while True:
print('I am working!')
time.sleep(0.5)
print_message()
I tried to kill the subprocess but after
os.kill(p.pid, signal.SIGKILL)
subprocess is still working and prints 'I am working!'
How can I finish subprocess and how to close gnome terminal?
If I selected completely wrong way. Can you show me working example?
New version of test_subprocess.py
#!/usr/bin/env python3
# coding=utf-8
import sys
from subprocess import signal
import time
def print_message():
while True:
print('I am working!')
time.sleep(0.5)
if signal.SIGKILL: # it is braking a loop when parent process terminate!
print('I am killing self!')
break
print_message()
Should I do it like above?
You could try the following:
p = Popen(['gnome-terminal', "--", path_to_file])
PIDs = p.pid
os.system("kill {0}".format(PIDs))
Popen.pid The process ID of the child process.
Note that if you set the shell argument to True, this is the process
ID of the spawned shell.
http://docs.python.org/library/subprocess.html
This will at least kill the correct process. Not sure if it will close the terminal.
Edit: to kill the process and close the terminal:
p = Popen(['gnome-terminal', '--disable-factory', '-e', path_to_file], preexec_fn=os.setpgrp)
os.killpg(p.pid, signal.SIGINT)
Credit to https://stackoverflow.com/a/34690644/15793575, whih I modified for your command:
--disable-factory is used to avoid re-using an active terminal so that we can kill newly created terminal via the subprocess handle
os.setpgrp puts gnome-terminal in its own process group so that
os.killpg() could be used to send signal to this group
Popen.pid
The process ID of the child process.
Note that if you set the shell argument to True, this is the process
ID of the spawned shell.
Try setting the shell argument of the Popen constructor to False. (p = Popen(['gnome-terminal', "--", path_to_file]) -> p = Popen(['gnome-terminal', "--", path_to_file], shell=False)). I had a similar issue not long ago - this fixed it for me.

How to get the pid of the process started by subprocess.run and kill it

I'm using Windows 10 and Python 3.7.
I ran the following command.
import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)
The .exe file launched with this command, I want to force-quit when the button is clicked or when the function is executed.
Looking at a past question, it has been indicated that the way to force quit is to get a PID and do an OS.kill as follows.
import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)
However, I don't know how to get the PID of the process started in subprocess.run.
What should I do?
Assign a variable to your subprocess
import os
import signal
import subprocess
exeFilePath = "C:/Users/test/test.exe"
p = subprocess.Popen(exeFilePath)
print(p.pid) # the pid
os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL
In same cases the process has children
processes. You need to kill all processes to terminate it. In that case you can use psutil
#python -m pip install —user psutil
import psutil
#remember to assign subprocess to a variable
def kills(pid):
'''Kills all process'''
parent = psutil.Process(pid)
for child in parent.children(recursive=True):
child.kill()
parent.kill()
#assumes variable p
kills(p.pid)
This will kill all processes in that PID

Do something when an os.system has an update for systemctl

I have code that currently looks like so:
import os
os.system("journalctl -f")
This watches journalctl live and whenever journalctl updates, it is posted in stdout.
I'm curious on how I would go about doing something when this is updated, for example:
import os
os.system("journalctl -f")
if if_something_new:
do_something(text)
Not sure what I can use to go about this, thanks in advance!
You can open the process with Popen and keep it alive by using while with readlines from stdout:
import subprocess
command = 'journalctl -f'
p = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1, shell=True)
while True:
if 'something' in p.stdout.readline():
doSomething

Is there a module can be used as FindWindow API in python

On Windows there is a WinAPI: FindWindow that you can use to get window handle of a existing window and use this handle to send message to it. Is there a python module can do that too? Find a window & communicate with it?
If this module do exist, could the same mechainsm be able applied on Ubuntu too?
Thanks a lot!
You can execute your commands with a subprocess:
import subprocess
import time
process = subprocess.Popen("echo 'start' & sleep 60 & echo 'stop'", shell=True)
time.sleep(60) # Maybe you want a timer...
The you have two options of closing, use terminate or kill methods in the Popen returned object or simulate a Ctrl. + C
import subprocess
import time
process = subprocess.Popen(cmd, shell=True)
time.sleep(5)
process.terminate() # Or kill
Simulate de ctrl + c:
import subprocess
import time
import os
import signal
process = subprocess.Popen(cmd, shell=True)
time.sleep(5)
os.kill(process.pid, signal.SIGINT) # Ctrl. + C
If you want to get the output you can use:
process.communicate()[0].strip()
Which gives you a string.
If you want a console GUI, you can use a command like:
gnome-terminal -x sh yourCommand
Or the equivalent for the terminal you have installed.

Opening an external program

I'm the Python beginner and I have a task to do. I have to write a function, that opens a program (.bin), execute it so I can see the results. This program requires 2 arguments from command line. I used os.spawnv, but it doesn't work...
#!/usr/bin/python
import sys
import os
def calculate_chi():
if len(sys.argv)>1:
pdb_name=sys.argv[1]
dat_name=sys.argv[2]
crysol='/usr/bin/crysol'
os.spawnv(os.P_NOWAIT,crysol,[crysol,pdb_name,dat_name])
def main():
calculate_chi()
Can you help me?
You can use python subprocess module:
import subprocess
proc = subprocess.Popen(['/usr/bin/crysol', sys.argv[1], sys.argv[2]], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while proc.poll() is None:
out = proc.stdout.readline() #read crystol's output from stdout and stderr
print out
retunValue = proc.wait() #wait for subprocess to return and get the return value
Use subprocess. It was intended to replace spawn.
import subprocess
subprocess.call([crysol, pdb_name, dat_name])
Everyone uses subprocess.Popen these days. An example call to your process would be
process = Popen(["/usr/bin/crysol", pdb_name, dat_name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Categories