2017-03-18 67 views
0

我试图从各种API请求数据。服务器必须同时调用,我知道我需要使用多线程,但我无法弄清楚如何以我想要的方式返回数据,这里是一个示例。如何多线程函数,从API调用返回数据

import requests 
import time 
import threading 

t = time.strftime('%m/%d/%Y %H:%M:%S') 
def getBitstamp(): 
    data = requests.get('https://www.bitstamp.net/api/ticker/') 
    data = data.json() 
    ask = round(float(data['ask']),2) 
    bid = round(float(data['bid']),2) 
    print 'bitstamp', time.strftime('%m/%d/%Y %H:%M:%S') 
    return ask, bid 

def getBitfinex(): 
    data = requests.get('https://api.bitfinex.com/v1/pubticker/btcusd') 
    data = data.json() 
    ask = round(float(data['ask']),2) 
    bid = round(float(data['bid']),2) 
    print 'finex', time.strftime('%m/%d/%Y %H:%M:%S') 
    return ask, bid 

while True: 
    bitstampBid, bitstampAsk rate = thread.start_new_thread(getBitstamp) 
    bitfinexAsk, bitfinexBid = thread.start_new_thread(getBitfinex) 
    #code to save data to a csv 
    time.sleep(1) 

似乎线程不喜欢返回多个(甚至任何值)我想我误解了库的工作原理。

编辑删除错误rate变量

回答

0

你需要决定是否要使用高级别Threading模块或低电平thread。 如果太迟然后使用import thread而不是import threading

接下来,你还需要传递一个元组内thread运行函数的参数。如果你没有,你可以传递一个空的元组,如下所示。

bitstampBid, bitstampAsk, rate = thread.start_new_thread(getBitstamp,()) 
bitfinexAsk, bitfinexBid = thread.start_new_thread(getBitfinex,()) 

该程序现在执行,如何运行到单独的错误,您可能想要调试。
这里有几个我注意到的错误。
getBitstamp()返回rate,但是,在getBitstamp()中未定义rate。对此编程错误。

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 
Type "copyright", "credits" or "license()" for more information. 
>>> ================================ RESTART ================================ 
>>> 

Traceback (most recent call last): 
    File "C:\amPython\multiThreading1.py", line 28, in <module> 
    bitstampBid, bitstampAsk = thread.start_new_thread(getBitstamp,()) 
TypeError: 'int' object is not iterable 
>>> bitstamp 03/18/2017 00:41:33 

有关多线程的一些想法,请参阅on this SO post,这可能对您有用。

+0

对不起'速度'并不意味着在那里。您链接到的帖子没有帮助 –

+0

我解决了这个帖子http://stackoverflow.com/questions/41711357/python-how-to-multi-thread-a-function-that-returns-multiplevalue哈哈还注意到,恰巧是我在1年前将你的帖子与你联系在一起 –