Day1:Python-threading

多线程处理并发-threading

一分钟了解threading的方法

threading提供了一个比thread模块更高层的API来提供线程的并发性。这些线程并发运行并共享内存。

  • 实例化Thread对象 threading.Thread,使用start()
  • threading.activeCount() 获取进程数
  • threading.enumerate() 返回当前运行中Thread的对象列表
  • setDaemon(True) 设置后台服务

话不多说,上代码:

# -*-coding:utf-8-*-
__author__ = 'xihu'

import time
import threading

def worker():
    print "worker!"
    time.sleep(1) # 亲测:将本行放在输出之前,执行程序不会打印(放置后台);但是放在后面为什么会有输出
    return

start = time.time()

# 并发
for i in xrange(5):
    t = threading.Thread(target=worker)
    # 设置后台进程
    t.setDaemon(True)
    t.start()

# threading.activeCount()包含主进程的个数
print "current has %d threads" % (threading.activeCount() - 1)

# threading.enumerate()返回当前运行中Thread的对象列表
for item in threading.enumerate():
    print item

end = time.time()
print end - start

# # 非并发
# if __name__ == "__main__":
#     start = time.time()
#     for i in xrange(5):
#         worker()
#     end = time.time()
#     print end - start #运行时间

运行对比:

#并发:
worker!worker!

worker!worker!

worker!
 current has 5 threads
<_MainThread(MainThread, started 140735323890432)>
<Thread(Thread-1, started daemon 4539203584)>
<Thread(Thread-4, started daemon 4551823360)>
<Thread(Thread-3, started daemon 4547616768)>
<Thread(Thread-2, started daemon 4543410176)>
<Thread(Thread-5, started daemon 4556029952)>
运行时间:0.00204181671143

# 非并发
worker!
worker!
worker!
worker!
worker!
运行时间:5.01394915581

遇到问题:
1、使用并发引入threading,运行程序直接报错:AttributeError: ‘module’ object has no attribute ‘Thread’
尴尬!因为开始没注意文件名是threading…所以以后文件名尽量避免使用保留字
2、设置后台运行程序:将本行sleep放在输出之前,执行程序不会打印(放置后台);但是放在后面为什么会有输出

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#!/usr/bin/env python #coding: utf-8 import os from time import time from datetime import datetime from netmiko import ConnectHandler from openpyxl import Workbook from openpyxl import load_workbook def read_device_excel( ): ip_list = [] wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx') ws1 = wb1.get_sheet_by_name("Sheet1") for cow_num in range(2,ws1.max_row+1): ipaddr = ws1["a"+str(cow_num)].value ip_list.append(ipaddr) return ip_list def get_config(ipaddr): session = ConnectHandler(device_type="huawei", ip=ipaddr, username="mtlops", password="cisco,123", banner_timeout=300) print("connecting to "+ ipaddr) print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr)) # config_data = session.send_command('screen-length 0 temporary') # config_data = session.send_command('dis cu | no-more ') # command = 'display version | display cpu-usage | display memory-usage' # config_data = session.send_command(command) commands = ['display version', 'display cpu-usage', 'display memory-usage'] config_data = '' for cmd in commands: output = session.send_command_timing(cmd) config_data += f'{cmd}\n{output}\n' session.disconnect() return config_data def write_config_to_file(config_data,ipaddr): now = datetime.now() date= "%s-%s-%s"%(now.year,now.month,now.day) time_now = "%s-%s"%(now.hour,now.minute) #---- Write out configuration information to file config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date verify_path = os.path.exists(config_path) if not verify_path: os.makedirs(config_path) config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name print ('---- Writing configuration: ', config_filename) with open( config_filename, "w",encoding='utf-8' ) as config_out: config_out.write( config_data ) return def main(): starting_time = time() ip_list = read_device_excel() for ipaddr in ip_list: hwconfig = get_config(ipaddr) write_config_to_file(hwconfig,ipaddr) print ('\n---- End get config threading, elapsed time=', time() - starting_time) #======================================== # Get config of HUAWEI #======================================== if __name__ == '__main__': main() 加一段gevent,def run_gevent()
05-26

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值