2016-05-12 71 views
0

我有一个python程序正在运行。它基本上不会连接并维持该连接,即程序不会再次输入bash外壳,直到手动终止。类似下面,需要并行运行相同的python文件

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

我想同monitor.py并行各种这样ssh连接运行。他们都是彼此独立的,不需要交换信息。我可以通过MultithreadingMultiprocessing来实现吗?

+0

您可以多次运行monitor.py,或者可以使其成为多线程,或者甚至可以派生多个子项。 – 2016-05-12 07:45:15

+0

多线程将是最好的这种情况下 –

回答

1

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

进口多为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中,修改很少 - 也许没有修改 - 但是如果你使用Python 3,你也应该调查concurrent.futures)。

+0

我试着用我的函数做ssh连接...这也可以...谢谢... ! :) – nidHi

1

您可以通过多个线程来实现您在问题中提到的内容。下面的代码是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 
+0

我试着用ssh连接...这个工程...谢谢:) – nidHi

相关问题