簡體   English   中英

如何使用 Python 找到正在運行的進程的位置

[英]How could I find the location of a running process using Python

我需要在我正在制作的程序中找到網絡瀏覽器的位置。

我決定通過運行瀏覽器 window 然后找到它的路徑來做到這一點。 我看過 psutil 但仍然不知道該怎么做。

我這樣做是因為我似乎無法使用 webbrowser 庫打開一個新的 window,無論我告訴它與否,它都會在新選項卡中打開。 所以我打算使用這里解釋的命令: http://kb.mozillazine.org/Command_line_arguments#List_of_command_line_arguments_.28incomplete.29

我在 Windows 10 上使用 Python 3.8.6

終於找到了使用 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 function 的 name 變量相同。

鏈接到原始代碼(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM