并行需要 运行 相同的 python 文件

Need of running the same python file in parallel

我有一个 python 程序 运行ning。它基本上是建立一个 ssh 连接并维持该连接,即程序不会再次进入 bash shell 直到手动终止。如下所示,

bash-4.1$ python monitor.py
CONNECTION MADE
one done...
two done...
three done...
.
.
.

我想将 monitor.py 与 运行 并行用于各种此类 ssh 连接。它们都是相互独立的,不需要交换信息。我可以通过 MultithreadingMultiprocessing 实现吗?

您可以创建多个线程来实现您在问题中提到的内容。下面的代码是 Python 中的多线程示例。用你的文件试试。

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

输出

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

这是一个类似的示例,它使用多处理而不是多线程(有关文档,请参阅 the official docs )。 Multiprocessing 的工作方式与多线程非常相似,但它绕过了全局解释器锁,因此允许您的脚本实际上同时 运行 不同的进程,并可能更好地利用有限的计算资源。

将多处理导入为 mp

def my_function(*args):
    print("Arguments: {0}".format(args))


class MyProcess(mp.Process):
    def __init__(self, target, args):
        mp.Process.__init__(self, target=target, args=args)

def main():
    a1 = MyProcess(target=my_function, args=("1st Process...",))
    a2 = MyProcess(target=my_function, args=("2nd Process...",))
    a3 = MyProcess(target=my_function, args=("3rd Process...",))
    a4 = MyProcess(target=my_function, args=("4th Process...",))

    proclist = [a1, a2, a3, a4]
    for proc in proclist:
        proc.start()

    for proc in proclist:
        proc.join()

if __name__ == '__main__':
    main()

输出:

Arguments: ('1st Process...',)
Arguments: ('2nd Process...',)
Arguments: ('3rd Process...',)
Arguments: ('4th Process...',)

虽然这些似乎是按固定顺序出现的,但如果您添加一个需要非确定性时间的任务,它们将按照完成的顺序出现。只需用您的代码替换 my_function 的内容,您就应该设置好了。 (注意:这使用 Python 2。在 Python 3 中同样适用,只需很少的修改——可能是 none——但是如果你在 Python 3 中,你还应该调查 concurrent.futures).