Home > Enterprise >  Transferring code from a file "main.py " in Jupyter Notebook
Transferring code from a file "main.py " in Jupyter Notebook

Time:12-19

I am trying to run the code in Jupiter notebook, but the figures in it do not run, help me to display the BTC graph in the pandas DataFrame using the "matplotlib" library

import websockets
import asyncio
import json
import time
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111)
fig.show()

xdata = []
ydata = []


def update_graph():
   ax.plot(xdata, ydata, color='g')
   ax.legend([f"Last price: {ydata[-1]}$"])

   fig.canvas.draw()
   plt.pause(0.1)


async def main():
    url = "wss://stream.binance.com:9443/stream?streams=btcusdt@miniTicker"
    async with websockets.connect(url) as client:
        while True:
           data = json.loads(await client.recv())['data']

           event_time = time.localtime(data['E'] // 1000)
           event_time = f"{event_time.tm_hour}:{event_time.tm_min}:   
           {event_time.tm_sec}"

           print(event_time, data['c'])

           xdata.append(event_time)
           ydata.append(int(float(data['c'])))

           update_graph()


if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

CodePudding user response:

Just remove this statement: if __name__ == '__main__':

CodePudding user response:

Jupyter runs your code differently than normal Python does.

When you run your code with python myfile.py, it sets a variable called __name__ to main. But when Jupyter runs your code, it doesn't set the variable.

Thus, when you say if __name__ == '__main__', it will never be executed in Jupyter because __name__ will never be main.

So, the solution is to remove the if statement and just keep the lines under it.

Change

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

to

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
  • Related