Python获取某个进程的CPU使用率、内存使用率

2019年4月17日 10:57 by wst

python运维

之前发文章获取系统资源使用状态,有老铁问怎么获取某个进程的资源使用状态,今天就来给大家解读下。

直接上代码:

"""
Author: deepinwst
Email: wanshitao@donews.com
Date: 19-4-17 上午10:44
"""

import psutil
import time
import json


KEY_LIST = [
    "status",  # 进程状态
    "pid",  # 进程号
    "create_time", # 进程启动时间
    "cpu_percent", # cpu占用率
    "username",  # 启动进程的用户
    "num_threads",  # 线程数量
    "memory_percent", # 内存使用率
    "cmdline", # 启动命令
    "cpu_affinity" # 使用了哪些核
]

def common_monitor(key_lis):
    """记录当前所有进程的状态"""
    pids = psutil.pids()
    pids_lis = []
    for pid in pids:
        if psutil.pid_exists(pid):
            pid_obj = psutil.Process(pid)
            dic = pid_obj.as_dict(attrs=key_lis)
            dic['cpu_affinity'] = str(dic['cpu_affinity'])
            dic['cmdline'] = ' '.join(dic['cmdline'])
            dic['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dic['create_time']))
            pids_lis.append(dic)

    return pids_lis

def one_process(pid, key_lis):
    """ 记录某个进程的状态 """
    pid_obj = psutil.Process(pid)
    dic = pid_obj.as_dict(attrs=key_lis)
    dic['cpu_affinity'] = str(dic['cpu_affinity'])
    dic['cmdline'] = ' '.join(dic['cmdline'])
    dic['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dic['create_time']))
    return dic
if __name__ == "__main__":
    ## 查看所有进程
    #res = common_monitor(KEY_LIST)
    #print(json.dumps(res, indent=4))
    # 请确保进程号存在
    res = one_process(5487, KEY_LIST)
    print(json.dumps(res, indent=4))

 


Comments(127) Add Your Comment

Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling settled to where I sat. “Name’s Bao.” He stated it exuberantly, as if solemn word of honour of his exploits were shared aside settlers about many a fire in Aeternum. He waved to a unimpassioned butt upset us, and I returned his token with a nod. He filled a eyeglasses and slid it to me across the stained red wood of the court prior to continuing. “As a betting chains, I’d be delighted to wager a adequate bit of coin you’re in Ebonscale Reach for the purpose more than the carouse and sights,” he said, eyes glancing from the sword sheathed on my hip to the bow slung across my back. http://images.google.ie/url?q=https://renewworld.ru/
Afhnac
buy lipitor 10mg generic <a href="https://lipiws.top/">order lipitor without prescription</a> lipitor brand
Ociryk
ciprofloxacin online - <a href="https://cipropro.top/">ciprofloxacin 1000mg pills</a> clavulanate cheap
Jnkgjj
purchase cipro generic - <a href="https://metroagyl.top/keflexcapsule/">keflex 500mg uk</a> buy augmentin 625mg sale
Moykpi
flagyl 400mg pill - <a href="https://metroagyl.top/">flagyl us</a> zithromax ca
Tqdhcx
buy ciprofloxacin 500mg without prescription - <a href="https://septrim.top/chloromycetin/">order chloromycetin without prescription</a> cost erythromycin 500mg
Jvbqaq
order valacyclovir 1000mg pill - <a href="https://gnantiviralp.com/diltiazem/">diltiazem 180mg generic</a> zovirax 400mg pill
Hnlqiq
ivermectin 2mg - <a href="https://keflexin.top/tetracycline/">order tetracycline generic</a> brand tetracycline
Eqzpql
purchase flagyl online cheap - <a href="https://metroagyl.top/clindamycin/">buy clindamycin pills for sale</a> zithromax 500mg price
Ooupun
order ampicillin sale <a href="https://ampiacil.top/doxycyclineantb/">vibra-tabs online</a> buy amoxil generic
Wacrvy
order furosemide 100mg generic - <a href="https://antipathogenc.com/prograf/">prograf 1mg ca</a> buy captopril 25mg online
Zgxwuj
buy metformin 1000mg without prescription - <a href="https://gnantiacidity.com/duricef/">cost duricef 250mg</a> purchase lincocin
Kvlrsb
order zidovudine 300 mg sale - <a href="https://canadiangnp.com/epivir/">buy lamivudine pills</a> buy zyloprim generic
Khqxdp
clozapine 50mg uk - <a href="https://genonlinep.com/frumil/">frumil price</a> buy famotidine pills for sale
Fmhzgk
buy quetiapine pills - <a href="https://gnkantdepres.com/desyrel/">trazodone drug</a> eskalith online buy
Jqpcnp
anafranil 50mg canada - <a href="https://antdeponline.com/paxil/">paxil 10mg pill</a> purchase sinequan online
Koilmr
cost hydroxyzine - <a href="https://antdepls.com/lexapro/">how to buy lexapro</a> order endep 25mg online cheap
Ubrdrw
oral clavulanate - <a href="https://atbioinfo.com/ampicillin/">buy acillin</a> order cipro 1000mg pill
Qwzdpx
amoxicillin brand - <a href="https://atbioxotc.com/ceftin/">buy ceftin online cheap</a> order cipro 500mg online
Hgtvai
order cleocin 300mg generic - <a href="https://cadbiot.com/chloramphenicol/">chloramphenicol ca</a> chloromycetin price
Apuofk
cost zithromax - <a href="https://gncatbp.com/">azithromycin brand</a> buy ciplox 500mg sale
Skjeqx
ivermectin 3mg over counter - <a href="https://antibpl.com/ascefaclor/">cheap cefaclor 500mg</a> order cefaclor 500mg pills
Keqeeo
order albuterol 2mg without prescription - <a href="https://antxallergic.com/advairdiskus/">advair diskus inhalator order</a> theo-24 Cr 400mg brand
Rqbsvn
generic medrol - <a href="https://ntallegpl.com/montelukast/">order montelukast</a> azelastine 10ml sprayer
Zmjagx
purchase desloratadine without prescription - <a href="https://rxtallerg.com/getaristocort/">buy cheap generic triamcinolone</a> order ventolin 4mg pill
Zlhfnu
buy glyburide for sale - <a href="https://prodeprpl.com/">buy glyburide for sale</a> buy dapagliflozin no prescription
Ndsbce
order metformin 1000mg for sale - <a href="https://arxdepress.com/">metformin 500mg pill</a> buy precose pills
Egrbux
prandin sale - <a href="https://depressinfo.com/">prandin without prescription</a> empagliflozin over the counter
Pgmhfs
terbinafine tablet - <a href="https://treatfungusx.com/adiflucanv/">buy fluconazole 200mg online cheap</a> buy grifulvin v medication
Crzljg
semaglutide 14 mg drug - <a href="https://infodeppl.com/">order semaglutide generic</a> cost DDAVP
Igkptb
nizoral drug - <a href="https://antifungusrp.com/clotrithasone/">buy lotrisone paypal</a> buy itraconazole without prescription
Yohaic
order lanoxin 250mg generic - <a href="https://blpressureok.com/trandate100/">trandate 100mg sale</a> lasix online
Wyrfal
buy generic hydrochlorothiazide for sale - <a href="https://norvapril.com/">hydrochlorothiazide oral</a> zebeta cost
Tdynkt
where can i buy metoprolol - <a href="https://bloodpresspl.com/">buy metoprolol tablets</a> purchase nifedipine generic
Pmxnqv
cost nitroglycerin - <a href="https://nitroproxl.com/indapamide/">indapamide 2.5mg for sale</a> buy valsartan 160mg sale
Gjlvns
rosuvastatin temple - <a href="https://antcholesterol.com/ezetimibe/">ezetimibe buy toast</a> caduet frame
Brovpv
order zocor 20mg without prescription - <a href="https://canescholest.com/atorvastatin/">lipitor fetch</a> lipitor 10mg generic
Djdqoe
buy viagra professional giant - <a href="https://edsildps.com/viagragold/">viagra gold online notion</a> levitra oral jelly online van
Nsfdsk
priligy lack - <a href="https://promedprili.com/">priligy either</a> cialis with dapoxetine bother
Wgptis
cenforce online wish - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra pills waistcoat
Rxglth
brand cialis hoarse - <a href="https://probrandtad.com/forzestpills/">forzest business</a> penisole great
Wsbrvr
cialis soft tabs online talk - <a href="https://supervalip.com/cavertapills/">caverta online buck</a> viagra oral jelly online soil
Vahtrh
brand cialis council - <a href="https://probrandtad.com/viagrasofttabs/">viagra soft tabs wing</a> penisole distinct
Ngjagp
cialis soft tabs online slight - <a href="https://supervalip.com/">cialis soft tabs glimmer</a> viagra oral jelly online behold
Vjuufw
cenforce 100mg over the counter - <a href="https://xcenforcem.com/brandviagrasildenafil/">brand viagra pills reef</a> brand viagra pills bosom
Vwtqfm
acne treatment achieve - <a href="https://placnemedx.com/">acne medication mist</a> acne medication stupid
Itwynn
inhalers for asthma wave - <a href="https://bsasthmaps.com/">asthma medication fully</a> asthma medication who
Yqihlw
uti treatment cautious - <a href="https://amenahealthp.com/">treatment for uti fill</a> uti treatment monstrous
Doaiaf
prostatitis medications interest - <a href="https://xprosttreat.com/">prostatitis medications thin</a> prostatitis pills older
Gpgtcw
valtrex best - <a href="https://gnantiviralp.com/">valacyclovir leave</a> valacyclovir precious
Yjclan
claritin woman - <a href="https://clatadine.top/">claritin vital</a> loratadine help
Ezryjg
priligy dark - <a href="https://prilixgn.top/">dapoxetine pavement</a> priligy throat
Ezhgdn
loratadine driver - <a href="https://clatadine.top/">loratadine assure</a> claritin wobbler
Hzazel
ascorbic acid surprise - <a href="https://ascxacid.com/">ascorbic acid share</a> ascorbic acid fortune
Spkqsn
promethazine toward - <a href="https://prohnrg.com/">promethazine death</a> promethazine mother
Yxnxto
biaxin pills mill - <a href="https://gastropls.com/">biaxin pills legend</a> cytotec blood
Utsbwp
florinef able - <a href="https://gastroplusp.com/">fludrocortisone pills massive</a> prevacid pills fruit
Diynps
aciphex pills - <a href="https://gastrointesl.com/">order aciphex generic</a> order domperidone pills
Gwgopz
buy generic dulcolax over the counter - <a href="https://gastroinfop.com/liv52/">liv52 oral</a> liv52 20mg brand
Dfjfna
bactrim 960mg cheap - <a href="https://ketiracet.com/">buy levetiracetam 500mg pill</a> tobra without prescription
Wmcxhl
zovirax over the counter - <a href="https://dupsteron.com/">order duphaston 10 mg for sale</a> dydrogesterone price
Kbwtzc
cheap dapagliflozin - <a href="https://sineqpin.com/">order sinequan 25mg sale</a> acarbose 25mg cost
Tvvnei
purchase griseofulvin generic - <a href="https://dipyrilx.com/">dipyridamole 25mg ca</a> lopid cheap
Ylhfyz
dimenhydrinate order - <a href="https://prasilx.com/">order prasugrel 10 mg sale</a> order actonel 35mg generic
Mvhumv
buy generic enalapril over the counter - <a href="https://vasolapril.com/">vasotec pills</a> zovirax without prescription
Zisbtl
cheap monograph 600 mg - <a href="https://etodograph.com/">monograph pills</a> pletal 100mg without prescription
Qkoeia
buy generic piroxicam online - <a href="https://rivastilons.com/">order rivastigmine 6mg online</a> buy rivastigmine for sale
Gwtlut
nootropil 800mg sale - <a href="https://nootquin.com/sinemet/">sinemet order online</a> buy sinemet without prescription
Vyxxwj
hydroxyurea canada - <a href="https://hydroydrinfo.com/methocarbamol/">buy generic methocarbamol</a> robaxin 500mg usa
Cywvpz
cheap divalproex 250mg - <a href="https://adepamox.com/acetazolamide/">acetazolamide 250 mg without prescription</a> order topiramate 100mg
Dmmfty
norpace online order - <a href="https://anorpica.com/lamotrigine/">lamotrigine 50mg us</a> buy thorazine 50 mg generic
Blzxfc
buy cyclophosphamide paypal - <a href="https://cycloxalp.com/">order cytoxan online</a> purchase trimetazidine online cheap
Dxoblq
buy aldactone 100mg generic - <a href="https://aldantinep.com/dipyridamole/">order dipyridamole generic</a> brand revia 50 mg
Dxlrwn
cyclobenzaprine order - <a href="https://abflequine.com/prasugrel/">buy cheap generic prasugrel</a> buy generic vasotec online
Okcyko
ondansetron 4mg tablet - <a href="https://azofarininfo.com/selegiline/">eldepryl online</a> order ropinirole 1mg
Ysxpen
ascorbic acid over the counter - <a href="https://mdacidinfo.com/">order generic ascorbic acid</a> prochlorperazine cost
Ptsrua
where can i buy durex gel - <a href="https://xalaplinfo.com/latanoprosteyedrops/">purchase latanoprost generic</a> zovirax for sale online
Seswvx
buy rogaine generic - <a href="https://hairlossmedinfo.com/finasteridefinp/">buy finpecia without prescription</a> finpecia generic
Pmricl
purchase arava generic - <a href="https://infohealthybones.com/alfacalcidol/">buy alfacip pills for sale</a> cartidin online
Ivqmto
atenolol 50mg oral - <a href="https://heartmedinfox.com/sotalol/">buy betapace paypal</a> buy generic carvedilol
Xuhfsf
verapamil 120mg generic - <a href="https://infoheartdisea.com/cardizem/">buy diltiazem 180mg sale</a> cost tenoretic
Dylwcj
atorvastatin price - <a href="https://infoxheartmed.com/lisinopril/">cost lisinopril</a> bystolic 20mg usa
Nmrhkb
cheap gasex - <a href="https://herbalinfomez.com/diabecon/">buy diabecon online</a> cheap diabecon online
Dnzidr
cheap lasuna generic - <a href="https://infoherbalmz.com/himcolin/">buy himcolin pills</a> order himcolin without prescription
Ykodgj
cheap norfloxacin tablets - <a href="https://gmenshth.com/">noroxin cost</a> buy generic confido
Juwtcj
buy finax for sale - <a href="https://finmenura.com/">where can i buy finax</a> uroxatral usa
Ghlnaa
buy speman tablets - <a href="https://spmensht.com/himplasia/">buy himplasia sale</a> buy finasteride without prescription
Gqkdau
hytrin 1mg oral - <a href="https://hymenmax.com/dutasteride/">dutasteride pill</a> buy priligy 60mg without prescription
Piselu
oxcarbazepine 300mg canada - <a href="https://trileoxine.com/levothyroxine/">cheap levothyroxine pills</a> buy synthroid 100mcg online
Nnzjsm
purchase imusporin generic - <a href="https://asimusxate.com/">cyclosporine for sale</a> colchicine 0.5mg us
Uydspq
how to buy lactulose - <a href="https://duphalinfo.com/">buy lactulose without a prescription</a> order betahistine 16 mg pill
Wauyme
deflazacort where to buy - <a href="https://lazacort.com/brimonidine/">order alphagan without prescription</a> buy brimonidine cheap
Pbwahl
how to get besifloxacin without a prescription - <a href="https://besifxcist.com/sildamax/">how to buy sildamax</a> purchase sildamax generic
Fkaqvf
order neurontin - <a href="https://aneutrin.com/sulfasalazine/">order azulfidine 500mg generic</a> cost azulfidine 500 mg
Gtqpmx
probalan without prescription - <a href="https://bendoltol.com/carbamazepine/">order carbamazepine 400mg generic</a> buy carbamazepine for sale
Payypg
buy celebrex 200mg generic - <a href="https://celespas.com/">buy celecoxib generic</a> indocin 75mg pill
Bymprh
mebeverine 135mg us - <a href="https://coloxia.com/">oral mebeverine 135 mg</a> buy pletal sale
Kswdyq
diclofenac usa - <a href="https://dicloltarin.com/aspirin/">generic aspirin</a> buy aspirin generic
Hvbugq
purchase rumalaya online cheap - <a href="https://rumaxtol.com/shallaki/">order shallaki online</a> amitriptyline pills
Tnenuy
order generic mestinon 60mg - <a href="https://mestonsx.com/">oral mestinon 60 mg</a> azathioprine 50mg price
Evzxxa
order voveran for sale - <a href="https://vovetosa.com/">order diclofenac generic</a> nimodipine order online
Plqdel
baclofen 10mg tablet - <a href="https://baclion.com/nspiroxicam/">piroxicam pills</a> feldene over the counter
Veutlx
buy meloxicam 15mg without prescription - <a href="https://meloxiptan.com/rtrizatriptan/">order toradol 10mg sale</a> buy toradol without a prescription
Hbeykx
cyproheptadine 4 mg sale - <a href="https://periheptadn.com/aszanaflex/">how to get tizanidine without a prescription</a> tizanidine online buy
Jnbbyl
buy trihexyphenidyl medication - <a href="https://voltapll.com/diclofenacgel/">how to purchase voltaren gel</a> purchase cheap voltaren gel
Dkiwax
omnicef us - <a href="https://omnixcin.com/aminocycline/"></a> how to get clindamycin without a prescription
Igeyjo
isotretinoin online - <a href="https://aisotane.com/asavlosulfon/">avlosulfon ca</a> buy deltasone 5mg generic
Nohmsz
buy prednisone 5mg without prescription - <a href="https://apreplson.com/permethrin/">buy generic zovirax</a> purchase zovirax generic
Ibqsfx
buy acticin cream - <a href="https://actizacs.com/asbenzac/">purchase benzoyl peroxide cream</a> buy tretinoin without a prescription
Vhczsr
betnovate for sale - <a href="https://betnoson.com/">order betamethasone 20 gm for sale</a> buy benoquin no prescription
Ueumaq
order flagyl without prescription - <a href="https://ametronles.com/">order flagyl 200mg sale</a> generic cenforce 50mg
Kntonr
augmentin 375mg tablet - <a href="https://alevonted.com/">levothyroxine order</a> levoxyl pills
Yhyhka
cleocin 150mg sale - <a href="https://indometnp.com/">order generic indocin</a> indomethacin 50mg without prescription
Jkhqws
losartan sale - <a href="https://cozartan.com/">purchase hyzaar generic</a> buy keflex 125mg generic
Icohwz
buy eurax medication - <a href="https://aeuracream.com/abactroban/">buy mupirocin generic</a> cheap aczone
Jizwij
how to get provigil without a prescription - <a href="https://sleepagil.com/melatonin/">buy meloset online cheap</a> buy melatonin 3 mg without prescription
Fbpxmd
order zyban online - <a href="https://bupropsl.com/shuddhaguggulu/">order shuddha guggulu pill</a> shuddha guggulu pills
Yntyou
xeloda drug - <a href="https://xelocap.com/">purchase capecitabine online</a> danazol tablet
Ssozpn
progesterone for sale - <a href="https://apromid.com/">cheap prometrium 100mg</a> order fertomid
Rulxqk
cheap fosamax - <a href="https://pilaxmax.com/medroxyprogesterone/">order provera 10mg for sale</a> buy medroxyprogesterone 5mg for sale
Beskgz
norethindrone 5 mg ca - <a href="https://norethgep.com/lumigan/">lumigan tablet</a> buy cheap generic yasmin
Cukcax
estradiol 1mg usa - <a href="https://festrolp.com/letrozole/">order femara 2.5mg</a> arimidex 1 mg drug
Qnhdyv
buy generic dostinex - <a href="https://adostilin.com/premarin/">premarin over the counter</a> cheap alesse tablets
Rksseu
гѓ—гѓ¬гѓ‰гѓ‹гѓійЂљиІ©гЃ§иІ·гЃ€гЃѕгЃ™гЃ‹ - <a href="https://jpaonlinep.com/">гѓ—гѓ¬гѓ‰гѓ‹гѓі еЂ‹дєєијёе…Ґ гЃЉгЃ™гЃ™г‚Ѓ</a> г‚ёг‚№гѓ­гѓћгѓѓг‚Ї е‰ЇдЅњз”Ё
Sqgyoi
シルデナフィル は通販での購 - <a href="https://jpedpharm.com/">バイアグラ 個人輸入 おすすめ</a> タダラフィル 副作用
Hrtwsu
プレドニン 値段 - <a href="https://jpanfarap.com/jpaaccutane/">イソトレチノイン 薬局で買える</a> アキュテインは薬局で買える?
Otfawk
eriacta monkey - <a href="https://eriagra.com/dapcalisb/">apcalis near</a> forzest mystery