如何 运行 函数内函数的多线程 - Python

How to run Multi-Threading for function within function - Python

Python初学者!!

from threading import Thread
from time import sleep

devices = ['1.1.1.1','2.2.2.2']

def conn(device):
    connect = ConnectHandler(device_type='cisco_ios', 
                             username='kiran', ip=device, password='ciscossh',secret='ciscoen')
    print 'connection successful'
    def commmand():
        value = connect.send('sh int ip brief')
        print value

for device in devices:
   thread = Thread(target = conn, args = (device, ))
   thread.start()
   thread.join()
   print("thread finished...exiting")

输出:

连接成功

线程完成...退出

连接成功

线程完成...退出

问题:不读取第二个函数 command(),是否需要调用第一个函数内的第二个函数?

读取command()并构建函数。你只是在定义它之后永远不会使用这个函数。我建议你review functions in python

您的代码需要调整:

def conn(device):
    connect = ConnectHandler(device_type='cisco_ios', 
                             username='kiran', ip=device, password='ciscossh',secret='ciscoen')
    print 'connection successful'
    def commmand():
        value = connect.send('sh int ip brief')
        print value
    command() # call your function!!! otherwise it is useless...

我可以试着澄清一些可能对你有帮助的观点吗?

- 即使你定义了 command() 方法,它并没有被显式调用,所以它的答案当然不应该被打印出来。

- 您的线程现在的工作方式非常同步。当您使用 join() 时,它会阻止线程的执行直到它完成,并且由于您没有同时初始化其他线程,您的代码执行仍然很简单。如果符合您的兴趣,您可以考虑启动所有线程,然后在 after for 循环 for 循环中加入它们。

- 网络连接有时需要独立的核心资源,并且有单独的处理器或内存要求。在这种情况下,您可能想要探索 Python 的 multiprocessing 模块而不是 threading

- 如果您有兴趣启动多个线程|进程,每次迭代(for 循环),您可能想要考虑使用 Pool 对象,它可以在单个数据结构中为您提供多个线程。

希望这对您有所帮助。