在下面的代码中,我将应用程序名称分配给进程ID(硬编码),例如:在下面的代码中,1468是进程ID,outlook是进程名称。在硬编码值中输入了每个pid的cpu相关信息。 这里我想用进程名替换进程id,并且应该得到相应进程名输出的cpu相关信息,如值字典中所示。
预期输出
outlook: [
233.625,
336.15625,
43791.0,
168.21875,
94.859375
],
chrome: [
3713.625,
3396.15625,
36791.0,
628.21875,
48.859375
],
command prompt:[
3713.625,
396.15625,
3791.0,
628.21875,
48.859375
]
实际输出:
3796
12972
1468
process name for this pid outlook
{3796: [3713.625, 396.15625, 3791.0, 628.21875, 48.859375], 12972: [3713.625, 3396.15625, 36791.0, 628.21875, 48.859375], 1468: [233.625, 336.15625, 43791.0, 168.21875, 94.859375]}
代码:
import os, platform, subprocess, re
import sys
import psutil
import itertools
import json
#if __name__ == "__main__" :
if True:
dict = {'1468 ': 'outlook', '12972':'chrome', '3796': 'command prompt'}
values ={
1468 : [
233.625,
336.15625,
43791.0,
168.21875,
94.859375
],
12972: [
3713.625,
3396.15625,
36791.0,
628.21875,
48.859375
],
3796:[
3713.625,
396.15625,
3791.0,
628.21875,
48.859375
]
}
class pretty:
def printf(self, json_object):
print(json.dumps(json_object, sort_keys=True, indent=4, separators=
(',', ': ')))
def comparision(self):
for iter in values.keys():
print (iter)
for proc in psutil.process_iter():
if iter == proc.pid:
#print(iter)
print("process name for this pid" +" "+proc.name())
if iter == proc.pid:
print(values)
pretty.comparision("")
请帮我解决这个问题,我是python的新手
答案 0 :(得分:2)
避免使用dict
和values
作为变量名称,因为它们是dictionary
个关键字,并将它们用作变量会导致意外结果:
使用:
dict1 = {'1468 ': 'outlook', '12972':'chrome', '3796': 'command prompt'}
values1 ={
1468 : [
233.625,
336.15625,
43791.0,
168.21875,
94.859375
],
12972: [
3713.625,
3396.15625,
36791.0,
628.21875,
48.859375
],
3796:[
3713.625,
396.15625,
3791.0,
628.21875,
48.859375
]
}
>>> res = {}
>>> for key, value in dict1.items():
... res[dict1[key]] = values1[int(key)]
...
>>> res
{'chrome': [3713.625, 3396.15625, 36791.0, 628.21875, 48.859375], 'outlook': [233.625, 336.15625, 43791.0, 168.21875, 94.859375], 'command prompt': [3713.625, 396.15625, 3791.0, 628.21875, 48.859375]}
答案 1 :(得分:1)
你不能这样做吗
for key in dict:
print (dict[key], ":", values[int(key)])
如果需要的话,我可以添加更多解释。
答案 2 :(得分:0)
dict = {'1468': 'outlook', '12972':'chrome', '3796': 'command prompt'}
values ={1468 : [233.625,336.15625,43791.0,168.21875,94.859375],
12972: [3713.625,3396.15625,36791.0,628.21875,48.859375],
3796:[3713.625,396.15625,3791.0,628.21875,48.859375]}
new_dict={}
for k in values.keys():
new_dict[dict[str(k)]] = str(values[k])
print new_dict # this would give you a dictionary