【问题标题】:Killing processes via python通过python杀死进程
【发布时间】:2020-06-15 14:46:52
【问题描述】:

我对 python 的了解相当有限,所以我可能只是在黑暗中摸索......

我想要做的是打开一个文件,在里面写一些东西然后关闭它。

我的问题是,如果那个文件被打开了怎么办?

为了满足我的需要,它需要关闭,不管它发生了什么,所以我可以通过 python 应用程序打开它。

所以如果我无法打开一个打开的文件,我可以尝试强制关闭它,然后通过 python 打开它?

找到这个库:https://psutil.readthedocs.io/en/latest/

它有点像我想要的,也许我只是缺少方法。

它目前返回给我所有进程的列表,并给我可以用来杀死进程的 ID。(find_procs_by_name, kill_proc_tree)

虽然实际上,我想关闭在 excel 中打开的 test.csv 而不是关闭所有 excel,有什么想法可以实现吗?

【问题讨论】:

    标签: python process termination


    【解决方案1】:

    您可以像使用 shell 命令一样使用pgrep

    https://pypi.org/project/pgrep/

    通过条件获取你的 ID,然后按照 Andrew 的说法杀死它。

    问候!

    编辑:

    另一种使用 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
    

    问候。

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2021-11-29
      • 2020-03-02
      • 2014-11-24
      相关资源
      最近更新 更多