英文:
Kill application in linux using python
问题
I can help you with the translation. Here's the translated text:
我需要关于在Linux中终止应用程序的帮助
作为手动过程,我可以使用以下命令 -- ps -ef | grep "app_name" | awk '{print $2}'
它会给我作业号(jobids),然后我将使用命令 "kill -9 作业号(jobid)" 来终止应用程序。
我想要一个可以执行此任务的Python脚本。
我已经编写了以下代码
import os
os.system("ps -ef | grep app_name | awk '{print $2}'")
这会收集作业号(jobids),但它们以整数类型存在,因此我无法终止应用程序。
请问您能在这里提供帮助吗?
谢谢
英文:
I need one help regarding killing application in linux
As manual process I can use command -- ps -ef | grep "app_name" | awk '{print $2}'
It will give me jobids and then I will kill using command " kill -9 jobid".
I want to have python script which can do this task.
I have written code as
import os
os.system("ps -ef | grep app_name | awk '{print $2}'")
this collects jobids. But it is in "int" type. so I am not able to kill the application.
Can you please here?
Thank you
答案1
得分: 1
import subprocess
temp = subprocess.run("ps -ef | grep 'app_name' | awk '{print $2}'", stdin=subprocess.PIPE, shell=True, stdout=subprocess.PIPE)
job_ids = temp.stdout.decode("utf-8").strip().split("\n")
# sample job_ids will be: ['59899', '68977', '68979']
# convert them to integers
job_ids = list(map(int, job_ids))
# job_ids = [59899, 68977, 68979]
Then iterate through the job ids and kill them. Use os.kill()
for job_id in job_ids:
os.kill(job_id, 9)
Subprocess.run doc - https://docs.python.org/3/library/subprocess.html#subprocess.run
英文:
import subprocess
temp = subprocess.run("ps -ef | grep 'app_name' | awk '{print $2}'", stdin=subprocess.PIPE, shell=True, stdout=subprocess.PIPE)
job_ids = temp.stdout.decode("utf-8").strip().split("\n")
# sample job_ids will be: ['59899', '68977', '68979']
# convert them to integers
job_ids = list(map(int, job_ids))
# job_ids = [59899, 68977, 68979]
Then iterate through the job ids and kill them. Use os.kill()
for job_id in job_ids:
os.kill(job_id, 9)
Subprocess.run doc - https://docs.python.org/3/library/subprocess.html#subprocess.run
答案2
得分: 0
要在Python中终止一个进程,调用os.kill(pid, sig)
,其中sig = 9(SIGKILL的信号编号),pid = 要终止的进程ID(PID)。
要获取进程ID,使用os.popen
而不是上面的os.system
。或者,使用subprocess.Popen(..., stdout=subprocess.PIPE)
。在这两种情况下,调用.readline()
方法,并将其返回值转换为整数,使用int(...)
。
英文:
To kill a process in Python, call os.kill(pid, sig)
, with sig = 9 (signal number for SIGKILL) and pid = the process ID (PID) to kill.
To get the process ID, use os.popen instead of os.system above. Alternatively, use subprocess.Popen(..., stdout=subprocess.PIPE)
. In both cases, call the .readline()
method, and convert the return value of that to an integer with int(...)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论