繁体   English   中英

如何使用多线程简化以下 python 代码

[英]How to use Multi-threading to simplify following python code

我有以下 python 代码,该代码从 yahoo Finance 获取实时股票数据并将其更新到 excel 表中...有没有人通过使用多线程来简化它以提高性能(这样它会同时更新 ZBF57C906FA7D2BB66D07372E415 单元格)...这是代码

import bs4
import requests
import xlwings as xw
from multiprocessing import Process

from bs4 import BeautifulSoup

def bajparsePrice():
    baj_r=requests.get('https://in.finance.yahoo.com/quote/BAJFINANCE.NS/')
    baj_soup=bs4.BeautifulSoup(baj_r.text,"lxml")
    baj_price=baj_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return baj_price

def infyparsePrice():
    infy_r=requests.get('https://in.finance.yahoo.com/quote/INFY.NS/')
    soup=bs4.BeautifulSoup(infy_r.text,"lxml")
    infy_price=soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return infy_price

def relparsePrice():
    rel_r=requests.get('https://in.finance.yahoo.com/quote/RELIANCE.NS/')
    rel_soup=bs4.BeautifulSoup(rel_r.text,"lxml")
    rel_price=rel_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return rel_price

def sbinparsePrice():
    sbin_r=requests.get('https://in.finance.yahoo.com/quote/SBIN.NS/')
    sbin_soup=bs4.BeautifulSoup(sbin_r.text,"lxml")
    sbin_price=sbin_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return sbin_price

def canbkparsePrice():
    canbk_r=requests.get('https://in.finance.yahoo.com/quote/CANBK.NS/')
    canbk_soup=bs4.BeautifulSoup(canbk_r.text,"lxml")
    canbk_price=canbk_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return canbk_price

while True:

    wb = xw.Book('fetchlivedata.xlsx')
    sht1 = wb.sheets['Sheet1']
    sht1.range('B2').value = str(bajparsePrice())
    sht1.range('B3').value = str(infyparsePrice())
    sht1.range('B4').value = str(relparsePrice())
    sht1.range('B5').value = str(sbinparsePrice())
    sht1.range('B6').value = str(canbkparsePrice())

Joblib 是一个很好的了解,非常容易用于并行 for 循环。

示例(来自他们的网站):

>>> from joblib import Parallel, delayed
>>> from math import sqrt
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

链接: https://joblib.readthedocs.io/en/latest/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM