【问题标题】:Find processes by command in python在python中通过命令查找进程
【发布时间】:2017-10-27 16:24:14
【问题描述】:

在我的 Python 脚本中,我想检查 otherscript.py 当前是否正在 (Linux) 系统上运行。 psutil 库看起来是个不错的解决方案:

import psutil
proc_iter = psutil.process_iter(attrs=["name"])
other_script_running = any("otherscript.py" in p.info["name"] for p in proc_iter)

问题在于p.info["name"] 只给出了进程的可执行文件的名称,而不是完整的命令。因此,如果在系统上执行python otherscript.pyp.info["name"] 将只是该进程的python,我的脚本无法检测otherscript.py 是否是正在运行的脚本。

有没有一种简单的方法可以使用 psutil 或其他一些库进行此检查?我意识到我可以将ps 命令作为子进程运行并在输出中查找otherscript.py,但如果存在,我更喜欢更优雅的解决方案。

【问题讨论】:

    标签: python process psutil


    【解决方案1】:

    我想知道这是否有效

    import psutil
    proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
    other_script_running = any("otherscript.py" in p.info["cmdline"] for p in proc_iter)
    

    【讨论】:

      【解决方案2】:

      http://psutil.readthedocs.io/en/latest/#find-process-by-name 看一下检查 name()、cmdline() 和 exe() 的第二个示例。

      供参考:

      import os
      import psutil
      
      def find_procs_by_name(name):
          "Return a list of processes matching 'name'."
          ls = []
          for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
              if name == p.info['name'] or \
                      p.info['exe'] and os.path.basename(p.info['exe']) == name or \
                      p.info['cmdline'] and p.info['cmdline'][0] == name:
                  ls.append(p)
          return ls
      

      【讨论】:

        【解决方案3】:

        此代码正在检查正在进行的过程。 Linux 或 Window 无关紧要

        import psutil
        
        proc_iter = psutil.process_iter()
        for i in proc_iter:
            print(i)
        

        【讨论】:

          猜你喜欢
          • 2011-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-21
          • 1970-01-01
          • 2013-02-12
          • 2013-11-22
          相关资源
          最近更新 更多