是否可以并行运行以下Web查询?

时间:2014-06-06 22:42:02

标签: python multithreading parallel-processing modbus modbus-tk

我使用Python和modbus_tk package来轮询n PLC。每次轮询大约需要5秒钟。是否可以并行运行这些并且不需要n*5秒来获取所有数据?

我目前的代码:

for ip in ip_addresses:
    master = modbus_tcp.TcpMaster(host=ip_address)
    my_vals = (master.execute(1, cst.READ_HOLDING_REGISTERS, starting_address=15))
    return my_vals

2 个答案:

答案 0 :(得分:1)

我不了解modbus_tk,但您可以使用the threading library吗?为每个要轮询的IP地址创建1个线程。

这里有一些示例代码可以帮助您:

import threading

class Poller( threading.Thread ):
    def __init__( self, ipaddress ):
        self.ipaddress = ipaddress
        self.my_vals = None
        threading.Thread.__init__(self)

    def run( self ):
        master = modbus_tcp.TcpMaster(host=self.ipaddress)
        self.my_vals = (master.execute(1, cst.READ_HOLDING_REGISTERS, starting_address=15))


pollers = []
for ip in ip_addresses:
    thread = Poller(ip)
    pollers.append(thread)
    thread.start()

# wait for all threads to finish, and collect your values
retrieved_vals = []
for thread in pollers:
    thread.join()
    retrieved_vals.append(thread.my_vals)

# retrieved_vals now contains all of your poll results
for val in retrieved_vals:
    print val

多处理也可以在这里工作,虽然这对问题来说太过分了。由于这是一个I / O操作,因此它是线程的理想候选者。 GIL(全球翻译锁定)不会减慢你的速度或任何东西,线程的重量比过程轻。

答案 1 :(得分:0)

使用multiprocessing.imap_unordered。它允许您启动一个进程池,将作业发送到池中,并在它们进入时接收结果。

以下是下载大量网址的示例代码:

import multiprocessing, re, subprocess, sys

CMD_LIST = [
    ["wget", "-qO-", "http://ipecho.net/plain"],
    ["curl", '-s', "http://www.networksecuritytoolkit.org/nst/cgi-bin/ip.cgi"],
    ["curl", '-s', "v4.ident.me"],
    ["curl", '-s', "ipv4.icanhazip.com"],
    ["curl", '-s', "ipv4.ipogre.com"],
]


ip_pat = re.compile('[0-9.]{7,}')
pool = multiprocessing.Pool(5)
for output in pool.imap_unordered(subprocess.check_output, CMD_LIST):
    print 'output:',output
    m = ip_pat.search(output)
    if m:
        print 'GOT IP:', m.group(0)
        pool.terminate()
        sys.exit(0)

print 'no IP found'