【问题标题】:run code/tasks in parallel from one python script?从一个 python 脚本并行运行代码/任务?
【发布时间】:2014-03-20 02:24:22
【问题描述】:

在这段代码中,我只是从队列中拉出并在无限循环中处理消息。 因此,我通过 API 弹出基于 REST 的队列,解析消息,然后通过 Twilio 发送一条短信,并一次又一次地无限次地执行此操作。 我正在考虑规模,所以我想最大限度地利用时间并让这个循环在每个脚本中同时运行几次。

如何将此代码转换为同时运行 4 次,而不必执行文件四次。

  .....
  var = 1 
  while var == 1 :  # This constructs an infinite loop
    try:
        queue = CHECKQ.queue("name_of_queue")
        msgs = queue.get(max=1, timeout=None)
        url =  msgs['messages'][0]['body']
        msgId =  msgs['messages'][0]['id']
        delMsg = queue.delete(msgId)
        number = "1"+url
        message = client.messages.create(to=number, from_="+15555555555",
                    body="Here's the link to install the controller -        
                    http://someapp.com")
    except (IndexError):
        sleep(1)

【问题讨论】:

  • 你看过 Python 的 multiprocessing 模块吗?
  • 谢谢,会申请的。可能自己回答这个。
  • 顿悟...并发循环

标签: python multithreading parallel-processing python-multithreading


【解决方案1】:

我使用了一个混合了多处理的无限循环,这是一个启动新子进程而不是线程的库。

我开发了 2 个脚本/模块 sendTxtMsg() 和 getWorkOffQueue()。

    #!/usr/bin/env python 

    from lib.python.imports import *
    client = TwilioRestClient()

    def sendTxtMsg():
        try:
            work = getWorkOffQueue()
            number = json.dumps(work["phoneNumber"])
            message = client.messages.create(to=number, from_="+15555555555",
                      body="Here's the link to install the controller -                      
                      http://some.awesome.app/jelly")
            phonenumbersInsert(json.dumps(work))
        except(TypeError):
            pass
            print "Nothing on Queue"
        except Exception as e:
            print e
            log1.info(e)

并将它们组合到下面的一个模块中,该模块同时执行多次工作流,实质上是从一个...代码体中用许多手臂和手拉出队列。

    #!/usr/bin/env python                                                              

    from multiprocessing import Process
    from lib.python.imports import *

    def goGetEm():
        x = 1 
        while x == 1:
            sendTxtMsg()

     if __name__ == '__main__':
         Process(target=goGetEm).start()
         Process(target=goGetEm).start()
         Process(target=goGetEm).start()
         Process(target=goGetEm).start()

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2016-09-03
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2014-11-04
    • 2012-06-28
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多