主线程不在线程模块

时间:2017-05-08 16:25:32

标签: python-3.x python-multithreading

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文件中来绘制usd中比特币的值。

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

绘图和抓取似乎都运行良好但如果我同时执行这两项操作,我会收到错误main thread not in main loop。我搜索了很多,但无法解决这个问题

1 个答案:

答案 0 :(得分:0)

这里的问题是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()