[英]How to optimally use multi-threading with multi-processing in 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.