Array saving only the last inserted value (PYTHON)

Asked

Viewed 30 times

0

I have a script that captures all processes from the machine, using the library PSUTIL, But when you put it inside an array it is only saving the last value in memory, not all values.

OBS: I need the values within an array to make comparisons

If someone identifies the error, it will be of great help :)

import psutil, datetime

cpu_count = psutil.cpu_count()
process = []

for pid in psutil.pids():

    try:
        p = psutil.Process(pid)
        name = p.name()  # execute internal routine once collecting multiple info
        time = p.cpu_times()  # return cached value
        mem_percent = p.memory_percent(memtype="rss") # return cached value
        cpu_percent = p.cpu_percent(interval=1) / cpu_count # return cached value
        create_time = p.create_time()  # return cached value
        pid = p.ppid()  # return cached value
        status = p.status()  # return cached value
    except: continue

    process = [''+str(pid)+'',''+str(name)+'',''+str(cpu_percent)+'',''+str(mem_percent)+'',''+str(datetime.datetime.fromtimestamp(create_time).strftime("%Y-%m-%d %H:%M:%S"))+'',''+str(time)+'',''+str(status)+'']

for i in range(len(process)):
    print(process[i])

1 answer

1


Writing like this: process = [ this overriding the array, that is, each time you run this line, the array is created with an element, and in your case it displays only the last one. To add a new element to the array use append:

process.append( [''+str(pid)+'',''+str(name)+'',''+str(cpu_percent)+'',''+str(mem_percent)+'',''+str(datetime.datetime.fromtimestamp(create_time).strftime("%Y-%m-%d %H:%M:%S"))+'',''+str(time)+'',''+str(status)+''])

So you will be adding an item to the end of the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.