亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何執行函數列表并將數據傳遞給使用 asyncio 調用的適當函數

如何執行函數列表并將數據傳遞給使用 asyncio 調用的適當函數

九州編程 2021-06-08 13:58:37
我以前使用過請求,但后來我轉向 aiohttp + asyncio 來并行運行帳戶,但是我無法將邏輯放在我的腦海中。class Faked(object):    def __init__(self):        self.database = sqlite3.connect('credentials.db')    async def query_login(self, email):        print(email)        cur = self.database.cursor()        sql_q = """SELECT * from user WHERE email='{0}'""".format(email)        users = cur.execute(sql_q)        row = users.fetchone()        if row is None:            raise errors.ToineyError('No user was found with email: ' + email + ' in database!')        self.logger().debug("Logging into account '{0}'!".format(row[0]))        call_func = await self._api.login(data={'email': row[0],                                                'password': row[1],                                                'deviceId': row[2],                                                'aaid': row[3]})        return await call_func    async def send_friend_request(self, uid):        return await self._api.send_friend_request(uid)def main(funcs, data=None):    """   todo: fill  :rtype: object  """    tasks = []    if isinstance(funcs, list):        for func in funcs:            tasks.append(func)    else:        tasks.append(funcs)    print(tasks)    loop = asyncio.get_event_loop()    results = loop.run_until_complete(asyncio.gather(*tasks))    for result in results:        print(result)    return resultsif __name__ == '__main__':  # for testing purposes mostly    emails = ['[email protected]', '[email protected]', '[email protected]']我基本上只是想知道如何對多個函數進行排隊,在這種情況下,query_login 和 send_friend_request,同時還將正確的數據傳遞給上述函數,假設我同時在一個社交媒體應用程序上運行三個帳戶,這真的讓我大吃一驚,雖然我有使事情過于復雜的傾向,但任何幫助將不勝感激。
查看完整描述

2 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

Python 旨在通過解包運算符 * 或使用 lambda 使這變得相當容易

讓我們來看看吧。


callstack = [] # initialize a list to serve as our stack.

     # See also collections.deque for a queue.

然后我們可以定義我們的函數:


def somefunc(a, b, c): 

    do stuff...

然后將參數作為列表添加到堆棧中。


args = [a, b, c]

callstack.append((somefunc, args)) # append a tuple with the function

            # and its arguments list.


# calls the next item in the callstack

def call_next(callstack):

    func, args = callstack.pop() # unpack our tuple

    func(*args) # calls the func with the args unpacked

* 運算符將您的列表解包并按順序提供它們作為參數。您還可以使用雙星運算符 (**) 解壓縮關鍵字參數。


def call_next(callstack):

    func, args, kwargs = callstack.pop() # unpack our tuple

    func(*args, **kwargs) # calls the func with both args and kwargs unpacked.

另一種方法是創建一個 lambda。


def add(a, b):

    return a + b


callstack = []


callstack.append(lambda: add(1, 2))

callstack.pop()() # pops the lambda function, then calls the lambda function, 

                  # which just calls the function as you specified it.

瞧!所有功勞都歸功于另一個線程中的作者。這里有一個問題:如果您將對象作為參數傳遞,它將作為引用傳遞。請小心,因為您可以在堆棧中調用對象之前對其進行修改。


def add(a, b, c):

    return a + b + c


badlist = [1,2,3]

callstack.append((somefunc, badlist))

badlist = [2, 4, 6]

callstack.append((somefunc, badlist))


while len(callstack) > 0:

    print(call_next(callstack))


# Prints:

12

12

你可以在 *args 版本中解決這個問題:


# make a shallow copy and pass that to the stack instead.

callstack.append((somefunc, list(badlist))) 

在 lambda 函數中,整個事物都在調用時進行評估,因此即使通常不是引用的事物也表現得像引用。上述技巧不起作用,因此在創建 lambda 之前根據需要進行任何復制。


查看完整回答
反對 回復 2021-06-29
  • 2 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號