我知道这与/proc有关,但我并不是很熟悉它。
psutil
模块是一个标准的解决方案。import psutil,getpass,os
user_name = getpass.getuser()
process_dict = {proc.pid:proc.name() for proc in psutil.process_iter() if proc.username() == user_name}
这将生成一个字典,以进程ID为键,以当前用户进程的进程名称为值。
这种方法看起来不错,但在我的Windows服务器机器上(我没有管理员权限),我无法获取proc.username()
而不出现psutil.AccessDenied
异常。所以我尝试在辅助程序中捕获异常,结果遇到了另一个奇怪的错误,因此我放弃了整个想法,并基于tasklist
命令构建了一个仅适用于Windows的解决方案:
tasklist /FI "USERNAME eq %USERNAME%" /FO CSV
经过适配Python并采用相同方便的pid => 用户名字典格式,翻译如下:
import csv,subprocess
def get_current_user_processes():
csv_output = subprocess.check_output(["tasklist","/FI","USERNAME eq {}".format(os.getenv("USERNAME")),"/FO","CSV"]).decode("ascii","ignore")
cr = csv.reader(csv_output.splitlines())
next(cr) # skip title lines
return {int(row[1]):row[0] for row in cr}
tasklist
仅保留当前用户进程,并使用csv输出格式,以便可以轻松地使用csv
模块进行解析。然后,我们仅保留前两列(名称和pid),并将pid转换为整数以确保正确性。psutil
。d = get_current_user_processes()
processes = [proc for proc in psutil.process_iter() if proc.pid in d]
我在这种情况下使用以下内容,检查它是否对您有帮助。目前它正在检查当前用户名,但您可以自定义它。
import psutil
processes = filter(lambda p: (p.username() == os.getlogin() and (p.name() == 'python')) , psutil.process_iter())
print(list(processes))
在使用了几天psutil之后,我发现这是最好的跨平台解决方案:
import psutil
def iter_user_procs():
# get username of the current Python process.
# Using this instead of something like os.getlogin() avoids cross-platform issues,
# such as Windows using USERDOMAIN\USERNAME instead of just USERNAME for process owners.
username = psutil.Process.username() # get username in format used by processes
# get username from the info dict to avoid AccessDenied errors. See docs for iter_procs().
for p in psutils.iter_procs(['username']):
if p.info['username'] == username:
yield p
import subprocess
ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE)
print ps.stdout.readlines()
import psutil
pids=[process.pid for process in psutil.process_iter() if
process.username == 'root']
process.username()
可能会引发psutil.AccessDenied
异常。因此无法以此方式进行过滤。 - Jean-François Fabrepopen非常好用,因为你可以通过grep、cut等运行指令。这样你就可以将信息量具体地调整到你想要的程度。