Python Forum
How to write a multi-threaded program for plotting interactively? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: How to write a multi-threaded program for plotting interactively? (/thread-18284.html)



How to write a multi-threaded program for plotting interactively? - rezaee - May-12-2019

I am trying to read data online from a website every 1 seconds using following code, then plot the result in real time. I mean I like to add new last_price in every second to the previous plot and update it.
import time
import requests


for i in range(2600):

    time.sleep(1)
    with requests.Session() as s:
        data = {'ContractCode' : 'SAFTR98'}
        r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()


    for key, value in r.items():
        print(r[key]['ContractCode'])
        last_prices = (r[key]['LastTradedPrice']) 
I used animation.FuncAnimation but didn't work because it plots all the results after the 2600 iterations is done or I stop the program! So I thought maybe I can do the work with multi-threading. But I don't know how exactly should I use it? I searched about but couldn't understand the examples and how should I map it to my problem?

This is not a duplicated question. In the mentioned link I tried to solve the problem using Animations but in this question I am trying to find a new way using multi-threading.


RE: How to write a multi-threaded program for plotting interactively? - rezaee - May-12-2019

No one knows about multithreading here?!


RE: How to write a multi-threaded program for plotting interactively? - Yoriz - May-12-2019

The time.sleep(1) is probably blocking the update of the plots.
i don't know what your using for a GUI but you could see either of the following to get an idea
https://python-forum.io/Thread-WxPython-How-to-deal-with-code-that-blocks-the-mainloop-freezing-the-gui
https://python-forum.io/Thread-Tkinter-How-to-deal-with-code-that-blocks-the-mainloop-freezing-the-gui


RE: How to write a multi-threaded program for plotting interactively? - rezaee - May-14-2019

(May-12-2019, 08:23 PM)Yoriz Wrote: The time.sleep(1) is probably blocking the update of the plots.
i don't know what your using for a GUI but you could see either of the following to get an idea
https://python-forum.io/Thread-WxPython-How-to-deal-with-code-that-blocks-the-mainloop-freezing-the-gui
https://python-forum.io/Thread-Tkinter-How-to-deal-with-code-that-blocks-the-mainloop-freezing-the-gui

I use usual matplotlib. What I am trying to do is just plot the result that I get from the post request in every second like many websites that show online prices of stocks, etc.