pythonisalive
Ⅰ python如何获取进程和线程状态
threading.active_count()
Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate().
active_count可以返回当前活动的线程枚举
我一般是这么用的
def getHeatsParallel(self): threads = [] for i in range(0, self.threadCount): t = threading.Thread(target=self.SomeFunction, name=str(i)) threads.append(t) t.start() for t in threads: t.join()
Ⅱ python中如何在父线程中检测其子线程是否处于运行状态
子线程有一个方法 is_alive()
运行时会返回Bool值True
Ⅲ python redis连接 线程安全么
在ConnectionPool之前,如果需要连接redis,我都是用StrictRedis这个类,在源码中可以看到这个类的具体解释:
redis.StrictRedis Implementation of the Redis protocol.This abstract class provides a Python interface to all Redis commands and an
implementation of the Redis protocol.Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server
使用的方法:
?
1
2
r=redis.StrictRedis(host=xxxx, port=xxxx, db=xxxx)
r.xxxx()
有了ConnectionPool这个类之后,可以使用如下方法
?
1
2
pool = redis.ConnectionPool(host=xxx, port=xxx, db=xxxx)
r = redis.Redis(connection_pool=pool)
这里Redis是StrictRedis的子类
简单分析如下:
在StrictRedis类的__init__方法中,可以初始化connection_pool这个参数,其对应的是一个ConnectionPool的对象:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class StrictRedis(object):
........
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
socket_connect_timeout=None,
socket_keepalive=None, socket_keepalive_options=None,
connection_pool=None, unix_socket_path=None,
encoding='utf-8', encoding_errors='strict',
charset=None, errors=None,
decode_responses=False, retry_on_timeout=False,
ssl=False, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None):
if not connection_pool:
..........
connection_pool = ConnectionPool(**kwargs)
self.connection_pool = connection_pool
在StrictRedis的实例执行具体的命令时会调用execute_command方法,这里可以看到具体实现是从连接池中获取一个具体的连接,然后执行命令,完成后释放连接:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# COMMAND EXECUTION AND PROTOCOL PARSING
def execute_command(self, *args, **options):
"Execute a command and return a parsed response"
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options) #调用ConnectionPool.get_connection方法获取一个连接
try:
connection.send_command(*args) #命令执行,这里为Connection.send_command
return self.parse_response(connection, command_name, **options)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
finally:
pool.release(connection) #调用ConnectionPool.release释放连接
在来看看ConnectionPool类:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class ConnectionPool(object):
...........
def __init__(self, connection_class=Connection, max_connections=None,
**connection_kwargs): #类初始化时调用构造函数
max_connections = max_connections or 2 ** 31
if not isinstance(max_connections, (int, long)) or max_connections < 0: #判断输入的max_connections是否合法
raise ValueError('"max_connections" must be a positive integer')
self.connection_class = connection_class #设置对应的参数
self.connection_kwargs = connection_kwargs
self.max_connections = max_connections
self.reset() #初始化ConnectionPool 时的reset操作
def reset(self):
self.pid = os.getpid()
self._created_connections = 0 #已经创建的连接的计数器
self._available_connections = [] #声明一个空的数组,用来存放可用的连接
self._in_use_connections = set() #声明一个空的集合,用来存放已经在用的连接
self._check_lock = threading.Lock()
.......
def get_connection(self, command_name, *keys, **options): #在连接池中获取连接的方法
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop() #获取并删除代表连接的元素,在第一次获取connectiong时,因为_available_connections是一个空的数组,
会直接调用make_connection方法
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection) #向代表正在使用的连接的集合中添加元素
return connection
def make_connection(self): #在_available_connections数组为空时获取连接调用的方法
"Create a new connection"
if self._created_connections >= self.max_connections: #判断创建的连接是否已经达到最大限制,max_connections可以通过参数初始化
raise ConnectionError("Too many connections")
self._created_connections += 1 #把代表已经创建的连接的数值+1
return self.connection_class(**self.connection_kwargs) #返回有效的连接,默认为Connection(**self.connection_kwargs)
def release(self, connection): #释放连接,链接并没有断开,只是存在链接池中
"Releases the connection back to the pool"
self._checkpid()
if connection.pid != self.pid:
return
self._in_use_connections.remove(connection) #从集合中删除元素
self._available_connections.append(connection) #并添加到_available_connections 的数组中
def disconnect(self): #断开所有连接池中的链接
"Disconnects all connections in the pool"
all_conns = chain(self._available_connections,
self._in_use_connections)
for connection in all_conns:
connection.disconnect()
execute_command最终调用的是Connection.send_command方法,关闭链接为 Connection.disconnect方法,而Connection类的实现:
?
1
2
3
4
5
6
7
class Connection(object):
"Manages TCP communication to and from a Redis server"
def __del__(self): #对象删除时的操作,调用disconnect释放连接
try:
self.disconnect()
except Exception:
pass
核心的链接建立方法是通过socket模块实现:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def _connect(self):
err = None
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
family, socktype, proto, canonname, socket_address = res
sock = None
try:
sock = socket.socket(family, socktype, proto)
# TCP_NODELAY
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# TCP_KEEPALIVE
if self.socket_keepalive: #构造函数中默认 socket_keepalive=False,因此这里默认为短连接
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
for k, v in iteritems(self.socket_keepalive_options):
sock.setsockopt(socket.SOL_TCP, k, v)
# set the socket_connect_timeout before we connect
sock.settimeout(self.socket_connect_timeout) #构造函数中默认socket_connect_timeout=None,即连接为blocking的模式
# connect
sock.connect(socket_address)
# set the socket_timeout now that we're connected
sock.settimeout(self.socket_timeout) #构造函数中默认socket_timeout=None
return sock
except socket.error as _:
err = _
if sock is not None:
sock.close()
.....
关闭链接的方法:
?
1
2
3
4
5
6
7
8
9
10
11
def disconnect(self):
"Disconnects from the Redis server"
self._parser.on_disconnect()
if self._sock is None:
return
try:
self._sock.shutdown(socket.SHUT_RDWR) #先shutdown再close
self._sock.close()
except socket.error:
pass
self._sock = None
可以小结如下
1)默认情况下每创建一个Redis实例都会构造出一个ConnectionPool实例,每一次访问redis都会从这个连接池得到一个连接,操作完成后会把该连接放回连接池(连接并没有释放),可以构造一个统一的ConnectionPool,在创建Redis实例时,可以将该ConnectionPool传入,那么后续的操作会从给定的ConnectionPool获得连接,不会再重复创建ConnectionPool。
2)默认情况下没有设置keepalive和timeout,建立的连接是blocking模式的短连接。
3)不考虑底层tcp的情况下,连接池中的连接会在ConnectionPool.disconnect中统一销毁。
Ⅳ 如何使用Python实现多进程编程
1.Process
创建进程的类:Process([group[,target[,name[,args[,kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。
方法:is_alive()、join([timeout])、run()、start()、terminate()。其中,Process以start()启动某个进程。
属性:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。
例1.1:创建函数并将其作为单个进程
importmultiprocessing
importtime
defworker(interval):
n=5
whilen>0:
print("Thetimeis{0}".format(time.ctime()))
time.sleep(interval)
n-=1
if__name__=="__main__":
p=multiprocessing.Process(target=worker,args=(3,))
p.start()
print"p.pid:",p.pid
print"p.name:",p.name
print"p.is_alive:",p.is_alive()
结果
12345678p.pid:8736p.name:Process-1p.is_alive:TrueThetimeisTueApr2120:55:122015ThetimeisTueApr2120:55:152015ThetimeisTueApr2120:55:182015ThetimeisTueApr2120:55:212015ThetimeisTueApr2120:55:242015
例1.2:创建函数并将其作为多个进程
importmultiprocessing
importtime
defworker_1(interval):
print"worker_1"
time.sleep(interval)
print"endworker_1"
defworker_2(interval):
print"worker_2"
time.sleep(interval)
print"endworker_2"
defworker_3(interval):
print"worker_3"
time.sleep(interval)
print"endworker_3"
if__name__=="__main__":
p1=multiprocessing.Process(target=worker_1,args=(2,))
p2=multiprocessing.Process(target=worker_2,args=(3,))
p3=multiprocessing.Process(target=worker_3,args=(4,))
p1.start()
p2.start()
p3.start()
print("ThenumberofCPUis:"+str(multiprocessing.cpu_count()))
forpinmultiprocessing.active_children():
print("childp.name:"+p.name+" p.id"+str(p.pid))
print"END!!!!!!!!!!!!!!!!!"
结果
1234567891011ThenumberofCPUis:4childp.name:Process-3p.id7992childp.name:Process-2p.id4204childp.name:Process-1p.id6380END!!!!!!!!!!!!!!!!!worker_1worker_3worker_2endworker_1endworker_2endworker_3
例1.3:将进程定义为类
importmultiprocessing
importtime
classClockProcess(multiprocessing.Process):
def__init__(self,interval):
multiprocessing.Process.__init__(self)
self.interval=interval
defrun(self):
n=5
whilen>0:
print("thetimeis{0}".format(time.ctime()))
time.sleep(self.interval)
n-=1
if__name__=='__main__':
p=ClockProcess(3)
p.start()
注:进程p调用start()时,自动调用run()
结果
12345thetimeisTueApr2120:31:302015thetimeisTueApr2120:31:332015thetimeisTueApr2120:31:362015thetimeisTueApr2120:31:392015thetimeisTueApr2120:31:422015
Ⅳ python进程能实现吗
序. multiprocessing
python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessing,只需要定义一个函数,Python会完成其他所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
回到顶部
1. Process
创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。
方法:is_alive()、join([timeout])、run()、start()、terminate()。其中,Process以start()启动某个进程。
属性:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。
例1.1:创建函数并将其作为单个进程
结果
1234567891011The number of CPU is:4child p.name:Process-3p.id7992child p.name:Process-2p.id4204child p.name:Process-1p.id6380END!!!!!!!!!!!!!!!!!worker_1worker_3worker_2end worker_1end worker_2end worker_3Ⅵ 如何用python写一个简单的12306抢票软件
看看这个可以吗功能:1:全自动爬所有车站列表2:爬所有车站之间的所有车次,过滤重复,保存文件爬过程中保存文件遇到http异常,停止继续脚本代码[python]viewplain#coding:utf-8__author__='watsy'#城市对象classcityObject(object):def__init__(self,abbr_pinyin="",full_pinyin="",chinaname="",shortCode=""):self.abbr_pinyin=abbr_pinyinself.full_piyin=full_pinyinself.chinaname=chinanameself.shortCode=shortCode#火车classtrainObject(object):def__init__(self,tid="",code="",start_city="",start_time="",end_city="",end_time="",full_time=""):self.tid=tidself.code=codeself.start_city=start_cityself.start_time=start_timeself.end_city=end_cityself.end_time=end_timeself.full_time=full_timedefget_writestr(self):#return("%s,%s,%s,%s,%s,%s,%s")%(self.tid,self.code,self.start_city.encode('utf-8'),self.start_time,self.end_city.encode('utf-8'),self.end_time,self.full_time)str_return=self.tid+",";str_return+=self.code+",";str_return+=self.start_city+",";str_return+=self.start_time+",";str_return+=self.end_city+",";str_return+=self.end_time+",";str_return+=self.full_time;returnstr_return#火车列表classtrainModel(list):defisExist(self,train):forsub_traininself:ifsub_train.code==train.code:returnTruereturnFalsedefsave(self):train=self[-1]withopen(("%s.txt")%(train.code),"w")aswf:printtrain.get_writestr()wf.write(train.get_writestr().encode('utf-8'))#解析城市defparserCitys(data):parser_citys=[]fororiginal_cityindata:iforiginal_cityandlen(original_city)>1:split_city=original_city.split('|')parser_city=cityObject(split_city[0],split_city[3],split_city[1],split_city[2])parser_citys.append(parser_city)printlen(parser_citys)returnparser_citys#生成url地址defgetBookingTrainListUrl(start_code,end_code,day):strUrl=("/otsquery/query/queryRemanentTicketAction.do?method=queryLeftTicket&")strUrl+=("orderRequest.train_date=%s&")%(day)strUrl+=("orderRequest.from_station_telecode=%s&")%(start_code)strUrl+=("orderRequest.to_station_telecode=%s&")%(end_code)strUrl+=("orderRequest.train_no=&trainPassType=QB&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str=00%3A00--24%3A00")returnstrUrltrains=trainModel()#解析预定车次列表defparser_booking_str(str_booking):json_book=json.loads(str_booking)datas=json_book['datas']ifdatasandlen(datas)>1:#printdatas.replace("","")trainlist=datas.replace("","").split("\\n")fortrain_strintrainlist:train_str_list=train_str.split(',')iflen(train_str_list)==17:str_id_and_code=train_str_list[1]str_start_city_and_time=train_str_list[2]str_end_city_and_time=train_str_list[3]str_full_time=train_str_list[4]#printstr_id_and_codestr_id=str_id_and_code[13:25]str_code=str_id_and_code[131:-7]#printstr_start_city_and_timeiflen(str_start_city_and_time)>50:str_start_city=str_start_city_and_time[43:-9]else:str_start_city=str_start_city_and_time[0:-9]str_start_time=str_start_city_and_time[-5:]#printstr_end_city_and_timeiflen(str_end_city_and_time)>50:str_end_city=str_end_city_and_time[42:-9]else:str_end_city=str_end_city_and_time[0:-9]str_end_time=str_end_city_and_time[-5:]tobj=trainObject(str_id,str_code,str_start_city,str_start_time,str_end_city,str_end_time,str_full_time)iftrains.isExist(tobj)==False:trains.append(tobj)trains.save()#打开城市列表页面u=urllib2.urlopen("mon/station_name.js?version=1.40")buffer=u.read()u.close()#获取列表buffer=buffer[20:-3]unformatter_citys=buffer.split('@')#得到城市parser_citys=parserCitys(unformatter_citys)city_length=len(parser_citys)today=datetime.date.today()torrow=datetime.timedelta(days=1)today=today+torrowday_str=("%s-%02d-%02d")%(today.year,int(today.month),int(today.day))print(day_str)strPath=os.getcwd()os.chdir("%s/train/"%strPath)foriinrange(1,city_length):forjinrange(0,len(parser_citys)-i):try:print("[%d%d]"%(i,j))sleep(0.09)strurl=getBookingTrainListUrl(parser_citys[i].shortCode,parser_citys[j].shortCode,day_str)url_add_header=urllib2.Request(strurl)url_add_header.add_header('X-Requested-With',"XMLHttpRequest")url_add_header.add_header('Referer',"/otsquery/query/queryRemanentTicketAction.do?method=init")url_add_header.add_header('Content-Type','application/x-www-form-urlencoded')url_add_header.add_header('Connection','keep-alive')resp=urllib2.urlopen(url_add_header)urlread=resp.read()resp.close()parser_booking_str(urlread)excepturllib2.HTTPErroraserr:print("error:[%s]url=[%s]")%(err,strurl)exit(1)os.chdir(strPath)printlen(trains)
Ⅶ python threads can only be started once
出现RuntimeError: threads can only be started once是因为你要启动的这个进程已经在执行了,无法再次启动它
Ⅷ python怎么判断线程的状态
is_alive():
Return whether the thread is alive.
http://docs.python.org/3/library/threading.html#threading.Thread.is_alive
Ⅸ python 多线程状态
threading.active_count()
Return the number of Thread objects currently alive. The returned count is
equal to the length of the list returned by enumerate().
active_count可以返抄回当前活动的线程枚举
我一般是这么用的
defgetHeatsParallel(self):
threads=[]
foriinrange(0,self.threadCount):
t=threading.Thread(target=self.SomeFunction,name=str(i))
threads.append(t)
t.start()
fortinthreads:
t.join()
不过我不关心几个活动,因为指定最多就是threadCount个线程
Ⅹ python 对于线程结束问题,注释那边怎么写结束语句呢sys.exit()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def _exitCheckfunc():
print "ok"
try:
while 1:
alive=False
if thread_.isAlive():
alive=True
if not alive:
break
time.sleep(1)
#为了使得统计时间能够运行,要捕捉 KeyboardInterrupt :ctrl-c
except KeyboardInterrupt, e:
traceback.print_exc()
print "consume time :",time.time()-start
threading._shutdown=_exitCheckfunc
自己在主线程中写一个死循环来接受ctrl+c的信号。