通过 python 终止进程
Killing processes via python
我对 python 的了解相当有限,所以我可能只是在黑暗中摸索...
我想做的是打开一个文件,在里面写一些东西然后关闭它。
我的问题是,如果那个文件被打开了怎么办?
为了满足我的需要,无论发生什么情况,它都需要关闭,所以我可以通过 python 应用程序打开它。
因此,如果我无法打开一个打开的文件,我可以尝试强制关闭它,然后通过 python?
打开它
找到这个库:https://psutil.readthedocs.io/en/latest/
它有点像我想要的,也许我只是缺少方法。
它目前 returns 给我一个所有进程的列表,并给了我可以用来终止进程的 ID。(find_procs_by_name, kill_proc_tree)
虽然实际上,我想关闭在 excel 中打开的 test.csv,而不是关闭所有 excel,我有什么想法可以实现吗?
您可以像使用 shell 命令一样使用 pgrep
。
https://pypi.org/project/pgrep/
通过条件获取你的ID然后按照安德鲁说的杀掉它
此致!
编辑:
另一种使用 psutils 的方法,循环查找给定名称的进程:
import psutil
# Get all proces in a list
pids = psutil.pids()
print("There is", len(pids), "Process")
#Search process with this string
name_like = "evolution"
# Loop checking for the pid "name_like"
i = 0
while i<len(pids):
print("i is", i)
print("pid (pids[i]) is", pids[i])
print("Proces name is", psutil.Process(pid=pids[i]).name())
if name_like in psutil.Process(pid=pids[i]).name():
print("KILL THIS F@*!& PROCESS")
i+=1
这是输出:
i is 181
pid (pids[i]) is 1834
Proces name is evolution-calendar-factory
KILL THIS F@*!& PROCESS
此致。
我对 python 的了解相当有限,所以我可能只是在黑暗中摸索...
我想做的是打开一个文件,在里面写一些东西然后关闭它。
我的问题是,如果那个文件被打开了怎么办?
为了满足我的需要,无论发生什么情况,它都需要关闭,所以我可以通过 python 应用程序打开它。
因此,如果我无法打开一个打开的文件,我可以尝试强制关闭它,然后通过 python?
打开它找到这个库:https://psutil.readthedocs.io/en/latest/
它有点像我想要的,也许我只是缺少方法。
它目前 returns 给我一个所有进程的列表,并给了我可以用来终止进程的 ID。(find_procs_by_name, kill_proc_tree)
虽然实际上,我想关闭在 excel 中打开的 test.csv,而不是关闭所有 excel,我有什么想法可以实现吗?
您可以像使用 shell 命令一样使用 pgrep
。
https://pypi.org/project/pgrep/
通过条件获取你的ID然后按照安德鲁说的杀掉它
此致!
编辑:
另一种使用 psutils 的方法,循环查找给定名称的进程:
import psutil
# Get all proces in a list
pids = psutil.pids()
print("There is", len(pids), "Process")
#Search process with this string
name_like = "evolution"
# Loop checking for the pid "name_like"
i = 0
while i<len(pids):
print("i is", i)
print("pid (pids[i]) is", pids[i])
print("Proces name is", psutil.Process(pid=pids[i]).name())
if name_like in psutil.Process(pid=pids[i]).name():
print("KILL THIS F@*!& PROCESS")
i+=1
这是输出:
i is 181
pid (pids[i]) is 1834
Proces name is evolution-calendar-factory
KILL THIS F@*!& PROCESS
此致。