#🔒 monitoring network need help with an error

73 messages · Page 1 of 1 (latest)

primal nebula
#

Hey, could need some help with this error I don't understand, if someone could also review my code and tell me what's good and what's wrong I take it, all the comments are written in french btw so glhf.

Here is the error : in collected_data_process
name_process = stats['name']
~~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not str

Here is the function where the error appear :

def collected_data_process(self):

    #tant que la queue est remplit alors on applique la suite du programme

        while not self.data_queue_process.empty():

            #en enregistre dans une variable les données stocké dans la queue

            stats = self.data_queue_process.get()




            #nom process

            name_process = stats['name']

            #% d'utilisation upload et download

            upload_percent = (float(stats['upload_percentage']))

            download_percent = (float(stats['upload_percentage']))

            #vitesse d'upload et download

            upload_speed = (float(stats['upload_speed'][:-4]))

            download_speed = (float(stats['download_speed'][:-4]))

            #quantité total d'upload et download

            upload_total = (float(stats['upload_total']))

            downlaod_total = (float(stats['download_total']))```
hoary oliveBOT
#

@primal nebula

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

primal nebula
#
            #remplisage du tableau

            if upload_speed and download_speed and download_speed and upload_percent:

                for row in self.tree_process.get_children():

                    self.tree_process.delete(row)

                time.sleep(1)

                self.tree_process.insert("", "end", values=(name_process, upload_speed, download_speed, upload_percent, download_percent))

How i get the queue data_queue_process : 

    def run_monitoring(self):

    #debug    print("run_monitoring début")

    #tant que self.monitorign est True la boucle va continuer et va en permanence appeller les autres fonctions

        while self.monitoring:

            #monitoring pc

            stats = get_network_stats()

            self.data_queue.put(stats)

            #monitoring process

            stats_process = get_network_process()

            self.data_queue_process.put(stats_process)```
#

Here the get_network_process() function Wich are in a different file but i import it properly I think.

def get_network_process(tick_update=1):

    def get_proc_info():

        #dictionnaire des info proc

        proc_info = {}

        #var des bytes

        pid_keys = list(pid2traffic.keys())

        #pour parcourir tout les processus par keys qui sont dans pid

        for pid in pid_keys :

            #pour chaque programme on a récuper son nom, son nombre de bytes reçus et envoyer

            for proc in psutil.process_iter(['pid', 'name']):

                try:

                    #on récupére les données envoyé et reçu par process id

                    net_io = proc.net_io_counters(pernic=True)

                    proc_info[proc.pid] = {

                        #nom du process

                        'name':proc.name(),

                        #données envoyé

                        'bytes_sent': net_io.bytes_sent,

                        #données reçu

                        'bytes_recv': net_io.bytes_recv,

                    }

                except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, AttributeError):

                    continue

        return proc_info

    proc_info_start = get_proc_info()

    time.sleep(tick_update)

    proc_info_end = get_proc_info()




    #trafic

    total_us = 0

    total_ds = 0

    #list de fin

    stats_process = []




    for pid, info in proc_info_end.items():

        print("for pid, info in proc info end used")

        if pid in proc_info_start:

            print("for pid, info in proc info end; if used")

            bytes_sent_start = proc_info_start[pid]['bytes_sent']

            bytes_recv_start = proc_info_start[pid]['bytes_recv']

            us = info['bytes_sent'] - bytes_sent_start

            ds = info['bytes_recv'] - bytes_recv_start```
#
            #traffic data total

            total_us += us

            total_ds += ds




            stats_process.append({

                'pid': pid,

                'name': info['name'],

                'upload_speed': get_size(us / tick_update) + '/s',

                'download_speed': get_size(ds / tick_update) + '/s',

                'upload_total':get_size(us),

                'download_total':get_size(ds),

            })

    #calcule percentage

    for stat in stats_process :

        stat['upload_percentage'] = (stat['upload_speed'] / total_us) * 100 if total_us > 0 else 0

        stat['download_percentage'] = (stat['download_speed'] / total_ds) * 100 if total_ds > 0 else 0

        stat['upload_speed'] = get_size(stat['upload_speed'] / tick_update) + '/s'

        stat['download_speed'] = get_size(stat['download_speed'] / tick_update) + '/s'

    return stats_process```
nimble torrent
primal nebula
#

How I do that ?

#

I just need to select the index ?

nimble torrent
#
my_list = [element_1, element_2] 

index_list = my_list[1] # is element_2
primal nebula
#

Ok i'll try

nimble torrent
#

Works?

primal nebula
#

Nope

#

List index out of range

nimble torrent
#

Ah sure

#

Hahaha

nimble torrent
#

Show me your list

primal nebula
#

Sure

#
stats_process = []
stats_process.append({

                'pid': pid,

                'name': info['name'],

                'upload_speed': get_size(us / tick_update) + '/s',

                'download_speed': get_size(ds / tick_update) + '/s',

                'upload_total':get_size(us),

                'download_total':get_size(ds),

            })```
nimble torrent
#

In this case you are saving a dictionary in a list. Do you want to access that dictionary?

primal nebula
#

Yes

#

I think I want if that make the rest of the code work

nimble torrent
#

First access the index that contains the dictionary in this case it is 0 because there is only a single element. Then access the key, example: [0]["pid"]

primal nebula
#

Ok

#

I try

nimble torrent
#

ready?

primal nebula
#

Doesn't work

nimble torrent
#

Error?

primal nebula
#

I try something else

#

Same error

#

List index out of range

nimble torrent
#

Show me how you're doing it now

primal nebula
#

I try with :

name_process = stats_process[0]['name']```
nimble torrent
#

For some reason I think the list is empty, can you print through the terminal that contains the list before using it?

primal nebula
#

Yes I think I can

#

Yes the list is empty

#

I don't get why tho

nimble torrent
#

Are you modifying the list elsewhere in your code?

primal nebula
#

I look

#

Nuh uh

#

The problem is somewhere on the function

nimble torrent
#

Your code is not very readable here, can you put it here?

#

!paste

hoary oliveBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

primal nebula
#

Yes of course

nimble torrent
#

I think I found the problem, give me a moment

nimble torrent
nimble torrent
#

I need to see the full traceback to see where it's wrong so I and others can help you better.

primal nebula
#

Ok but the terminal doesn't tell me any line is wrong in the function I send you

#

Do you mean about the whole script?

#

I currently can't provide it I have to move irl as soon I can I will send it here

nimble torrent
#

run your code and if Python finds an error it shows it to you

primal nebula
#

Wait 20 minutes

nimble torrent
#

bruh

primal nebula
#

Sorry but I'm in a subway rn

primal nebula
#

The equivalent in the paste is the line 16

nimble torrent
#

!traceback

hoary oliveBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

nimble torrent
#

I need this

primal nebula
#

Hooo ok

primal nebula
# nimble torrent I need this
Traceback (most recent call last):
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1967, in __call__      
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 861, in callit
    func(*args)
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\backends\_backend_tk.py",
line 142, in _on_timer
    super()._on_timer()
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\backend_bases.py", line 1193, in _on_timer
    ret = func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1427,
in _step
    still_going = super()._step(*args)
                  ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1121,
in _step
    self._draw_next_frame(framedata, self._blit)
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1140,
in _draw_next_frame
    self._draw_frame(framedata)
  File "C:\Users\10137072\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1766,
in _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\10137072\Monitoring_wip\monitoring_visu.py", line 289, in update_pie_graph
    self.collected_data_process()
  File "c:\Users\10137072\Monitoring_wip\monitoring_visu.py", line 224, in collected_data_process
    name_process = stats_process[0]['name']
                   ~~~~~~~~~~~~~^^^
IndexError: list index out of range```
nimble torrent
#

Hmmmmm To get the list you are calling a method called stats = self.data_queue_process.get() correct?

primal nebula
#

Yes sir

primal nebula
primal nebula
#

i don't understand how the method can be an issue, howe ever i just remark that my cade actually don't get any list or the list remain empty

primal nebula
#

i legit have no clue why it's still not working tho

hoary oliveBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.