如何强制执行下一个函数

时间:2016-10-04 15:14:30

标签: python twitter

我正在尝试执行twitterbot库定义的多个函数。我需要代码执行一个函数,然后是下一个函数,然后是下一个函数,或者是随机顺序。但是,该函数设计为循环运行。

我宁愿远离编辑实际的库,所以我正在寻找一个允许我只执行一次该函数的解决方案,继续执行下一个并从顶部循环。

Python有没有办法做到这一点?

from TwitterFollowBot import TwitterBot

my_bot = TwitterBot()
my_bot.sync_follows()

# Start of loop

my_bot.auto_fav("@asco", count=1000) 
# The above function persists to execute without continuing down
# Need bottom functions to also execute.
my_bot.auto_fav("ATSO", count=1000)
my_bot.auto_fav("BCY3", count=1000)
my_bot.auto_fav("ESIO", count=1000)

# End of loop

1 个答案:

答案 0 :(得分:1)

您可以使用对列表中函数的引用,然后使用random.shuffle。您可以使用threading.Thread来运行所有功能。我使用time.sleepfor作为示例来说明即使for循环未完成,每个线程的执行方式:

import random
import time
from threading import Thread

def a():
    for i in range(10000):
        print(i)
        time.sleep(1)
def b():
    for i in range(10000):
        print(i)
        time.sleep(2)
def c():
    for i in range(10000):
        print(i)
        time.sleep(3)
def d():
    for i in range(10000):
        print(i)
        time.sleep(4)
def e():
    for i in range(10000):
        print(i)
        time.sleep(5)

listOfFunctions = [a, b, c, d, e]
random.shuffle(listOfFunctions)


for i in listOfFunctions:
    Thread(target = i).start() # Use args=(your args) if you want to run each function with arguments