主线程不在线程模块中的主循环错误

问题描述:

import time 
import datetime as dt 
import urllib.request 
from bs4 import BeautifulSoup 
import matplotlib.pyplot as plt 
import matplotlib.animation as Animation 
from matplotlib import style 
import matplotlib 
import csv 
import threading 

style.use('fivethirtyeight') 
fig = plt.figure() 


def usd_in_bitcoin(): 
    try: 
     resp = urllib.request.urlopen("https://bitcoinwisdom.com/") 
    except Exception as e: 
     print(e) 
    text = resp.read() 

    soup = BeautifulSoup(text, 'html.parser') 
    intermediate = soup.find('tr', {"id": "o_btcusd"}) 
    ans = intermediate.find('td', {'class': 'r'}) 
    return ans.contents[0] 


def write_to_file(interval): 
    while True: 
     value = str(usd_in_bitcoin()) 
     unix_time = str(time.time()) 
     print(unix_time, value) 
     with open('bitcoin_usd.csv', 'a+') as file: 
      file.write(unix_time) 
      file.write("," + str(value)) 
      file.write('\n') 
     time.sleep(interval) 


def animate(i): 
    with open('bitcoin_usd.csv') as csv_file: 
     readcsv = csv.reader(csv_file, delimiter=',') 
     xs = [] 
     ys = [] 
     for row in readcsv: 
      if len(row) > 1: 
       x, y = [float(s) for s in row] 
       xs.append(dt.datetime.fromtimestamp(x)) 
       ys.append(y) 
     print(len(xs)) 
     dates = matplotlib.dates.date2num(xs) 
     # print(dates) 
     fig.clear() 
     plt.plot_date(dates, ys) 


def plotting(): 
    ani = Animation.FuncAnimation(fig, animate, interval=1000) 
    plt.show() 


def main(): 
    # plotting() 
    b = threading.Thread(name='making graph', target=plotting) 
    # a = threading.Thread(name='updating_csv', target=write_to_file, args=(5,)) 

    # a.start() 
    b.start() 


if __name__ == '__main__': 
    main() 

在上面的代码块中,我试图通过使用scraping来绘制比特币的值,然后将值放在csv文件中。主线程不在线程模块中的主循环错误

然后我读取csv文件来绘制图形。

无论是绘图还是抓图似乎都可以正常工作,但如果我同时执行这两种操作,我会收到一条错误消息,说main thread not in main loop。我搜索了很多,但没能解决这个问题

这里的问题是用线在main()

序列试试这个:

def main(): 
    a = threading.Thread(name='updating_csv', target=write_to_file, args=(5,)) 
    a.start() 
    b = threading.Thread(name='making graph', target=plotting) 
    b.start() 
    plotting()