【问题标题】:How could I find the location of a running process using Python如何使用 Python 找到正在运行的进程的位置
【发布时间】:2021-06-07 19:42:01
【问题描述】:

我需要在我正在制作的程序中找到网络浏览器的位置。

我决定通过运行浏览器窗口然后找到它的路径来做到这一点。我看过 psutil 但仍然不知道该怎么做。

我这样做是因为我似乎无法使用 webbrowser 库打开一个新窗口,无论我告诉它到哪里,它都会在一个新选项卡中打开。所以我打算使用这里解释的命令:http://kb.mozillazine.org/Command_line_arguments#List_of_command_line_arguments_.28incomplete.29

我在 Windows 10 上使用 Python 3.8.6

【问题讨论】:

    标签: python python-3.x process psutil


    【解决方案1】:

    终于用psutil找到了解决办法!

    import psutil
    
    def findPath(name):
        for pid in psutil.pids():
            if psutil.Process(pid).name() == name:
                return psutil.Process(pid).exe()
    
    print(findPath('firefox.exe'))
    

    这将遍历所有 pid 并检查 pid 名称是否与传递给 findPath 函数的 name 变量相同。

    【讨论】:

    • 如果多个进程同名但位置不同怎么办?
    【解决方案2】:

    Link to original code (psutil)

    我修改了原始代码以满足您的需求。不幸的是,我无法测试它们,因为我在 Android 平台上,而 TermuxPython 中的 psutil 模块不能由于安全/隐私原因访问(自 Android 更新以来)统计信息,因此如果它们不起作用,请告诉我

    简单的方法

    import psutil
    
    def findPath(name: str) -> list:
        ls: list = [] # since many processes can have same name it's better to make list of them
        for p in psutil.process_iter(['name', 'pid']):
            if p.info['name'] == name:
                ls.append(psutil.Process(p.info['pid']).exe())
        return ls
    

    更高级

    import os
    import psutil
    
    def findPathAdvanced(name: str) -> list:
        ls: list = [] # same reason as previous code
        for p in psutil.process_iter(["name", "exe", "cmdline", "pid"]):
            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(psutil.Process(p.info['pid']).exe())
        return ls
    

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 2021-04-08
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多