Python 网络编程
Python 提供了两个级别访问的网络服务。:
1,低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口的全部方法。
2,高级别的网络服务模块 SocketServer, 它提供了服务器中心类,可以简化网络服务器的开发。
socket()函数
Python 中,我们用 socket()函数来创建套接字,语法格式如下:
socket.socket([family[, type[, proto]]])
Socket 对象(内建)方法
Python 多线程
Python中使用线程有两种方式:函数或者用类来包装线程对象。
函数式:调用thread(_thread)模块中的start_new_thread()函数来产生新线程。
语法如下:
thread.start_new_thread ( function, args[, kwargs] )
例:
import _thread
import time
#为线程定义一个函数
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
#创建两个线程
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.exit(),他抛出SystemExit exception,达到退出线程的目的。
线程模块
Python2标准库中提供了两个模块thread和threading支持多线程。
thread有一些缺陷在Python3中弃用,为了兼容性,python3 将 thread 重命名为 “_thread”,在Python3中推荐直接使用threading。
1,threading.currentThread(): 返回当前的线程变量。
2,threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
3,threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
4,run(): 用以表示线程活动的方法。
5,start():启动线程活动。
6,join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
7,isAlive(): 返回线程是否活动的。
8,getName(): 返回线程名。
9,setName(): 设置线程名。
使用Threading模块创建线程
使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法:
import threading
import time
exitFlag = 0
class myThread (threading.Thread): #继承父类threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
#把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
#创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
#开启线程
thread1.start()
thread2.start()
print ("Exiting Main Thread")
线程同步
使用Thread(_thread)对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire方法和release方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到acquire和release方法之间。如下:
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
#创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
#开启新线程
thread1.start()
thread2.start()
#添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
#等待所有线程完成
for t in threads:
t.join()
print ("Exiting Main Thread")
线程优先级队列( Queue)
Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。
1,Queue.qsize() 返回队列的大小
2,Queue.empty() 如果队列为空,返回True,反之False
3,Queue.full() 如果队列满了,返回True,反之False
4,Queue.full 与 maxsize 大小对应
5,Queue.get([block[, timeout]])获取队列,timeout等待时间
6,Queue.get_nowait() 相当Queue.get(False)
7,Queue.put(item) 写入队列,timeout等待时间
8,Queue.put_nowait(item) 相当Queue.put(item, False)
9,Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
10,Queue.join() 实际上意味着等到队列为空,再执行别的操作