當前位置:首頁 » 編程語言 » python線程超時

python線程超時

發布時間: 2023-07-26 15:18:59

1. 為什麼python多線程這么慢

差不多是這樣子。多線程目前僅用於網路多線程採集, 以及性能測試。

其它的語言也有類似的情況,線程本身的特點導致線程的適用范圍是受限的。只有CPU過剩,而其它的任務很慢,此時用線程才是有益的,可以很好平衡等待時間,提高並發性能。

線程的問題主要是線程的安全穩定性。線程無法強制中止,同時線程與主進程共享內存,可能會影響主進程的內存管理。

在python里線程出問題,可能會導致主進程崩潰。 雖然python里的線程是操作系統的真實線程。

那麼怎麼解決呢?通過我們用進程方式。子進程崩潰後,會完全的釋放所有的內存和錯誤狀態。所以進程更安全。 另外通過進程,python可以很好的繞過GIL,這個全局鎖問題。

但是進程也是有局限的。不要建立超過CPU總核數的進程,否則效率也不高。

簡單的總結一下。
當我們想實現多任務處理時,首先要想到使用multiprocessing, 但是如果覺著進程太笨重,那麼就要考慮使用線程。 如果多任務處理中需要處理的太多了,可以考慮多進程,每個進程再採用多線程。如果還處理不要,就要使用輪詢模式,比如使用poll event, twisted等方式。如果是GUI方式,則要通過事件機制,或者是消息機制處理,GUI使用單線程。

所以在python里線程不要盲目用, 也不要濫用。 但是線程不安全是事實。如果僅僅是做幾個後台任務,則可以考慮使用守護線程做。如果需要做一些危險操作,可能會崩潰的,就用子進程去做。 如果需要高度穩定性,同時並發數又不高的服務。則強烈建議用多進程的multiprocessing模塊實現。

linux或者是unix里,進程的使用代價沒有windows高。還是可以接受的。

2. python 多線程如何延時

importtime
fromthreadingimportThread

##定時輸入
classk(object):
x=0
sleepTime=0
def__init__(self,sleepTime=0):
self.sleepTime=sleepTime
self.input_delay_test()
definput_delay(self):
self.x=input("pleaseinput ")
definput_delay_test(self):
thd=Thread(target=self.input_delay)
thd.daemon=True
thd.start()
time.sleep(self.sleepTime)
print(self.x,self.sleepTime,sep='')
[print(x,end='')forxinrange(10)]

k(4)

3. 求助python多線程,執行到100多個停止了

python 線程 暫停, 恢復, 退出
我們都知道python中可以是threading模塊實現多線程, 但是模塊並沒有提供暫停, 恢復和停止線程的方法, 一旦線程對象調用start方法後, 只能等到對應的方法函數運行完畢. 也就是說一旦start後, 線程就屬於失控狀態. 不過, 我們可以自己實現這些. 一般的方法就是循環地判斷一個標志位, 一旦標志位到達到預定的值, 就退出循環. 這樣就能做到退出線程了. 但暫停和恢復線程就有點難了, 我一直也不清除有什麼好的方法, 直到我看到threading中Event對象的wait方法的描述時.
wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
阻塞, 直到內部的標志位為True時. 如果在內部的標志位在進入時為True時, 立即返回. 否則, 阻塞直到其他線程調用set()方法將標准位設為True, 或者到達了可選的timeout時間.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
當給定了timeout參數且不為None, 它應該是一個浮點數,以秒為單位指定操作的超時(或是分數)。
此方法在退出時返回內部標志,因此除非給定了超時且操作超時,否則它將始終返回True。
Changed in version 2.7: Previously, the method always returned None.
2.7版本以前, 這個方法總會返回None.
<br>
利用wait的阻塞機制, 就能夠實現暫停和恢復了, 再配合循環判斷標識位, 就能實現退出了, 下面是代碼示例:
#!/usr/bin/env python
# coding: utf-8
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # 用於暫停線程的標識
self.__flag.set() # 設置為True
self.__running = threading.Event() # 用於停止線程的標識
self.__running.set() # 將running設置為True
def run(self):
while self.__running.isSet():
self.__flag.wait() # 為True時立即返回, 為False時阻塞直到內部的標識位為True後返回
print time.time()
time.sleep(1)
def pause(self):
self.__flag.clear() # 設置為False, 讓線程阻塞
def resume(self):
self.__flag.set() # 設置為True, 讓線程停止阻塞
def stop(self):
self.__flag.set() # 將線程從暫停狀態恢復, 如何已經暫停的話
self.__running.clear() # 設置為False
下面是測試代碼:
a = Job()
a.start()
time.sleep(3)
a.pause()
time.sleep(3)
a.resume()
time.sleep(3)
a.pause()
time.sleep(2)
a.stop()
<br>
測試的結果:
這完成了暫停, 恢復和停止的功能. 但是這里有一個缺點: 無論是暫停還是停止, 都不是瞬時的, 必須等待run函數內部的運行到達標志位判斷時才有效. 也就是說操作會滯後一次.
但是這有時也不一定是壞事. 如果run函數中涉及了文件操作或資料庫操作等, 完整地運行一次後再退出, 反而能夠執行剩餘的資源釋放操作的代碼(例如各種close). 不會出現程序的文件操作符超出上限, 資料庫連接未釋放等尷尬的情況.

4. python中requests請求超時 異常怎麼書寫

超時
你可以告訴requests在經過以timeout參數設定的秒數時間之後停止等待響應:
>>>requests.get('http://github.com',timeout=0.001)
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<mole>
requests.exceptions.Timeout:HTTPConnectionPool(host='github.com',port=80):Requesttimedout.(timeout=0.001)

用異常處理獲取超時異常就可以了,給你個例子,自己修改既可以

try:
requests.get('https://www.taobao.com/',timeout=0.1)
exceptrequests.exceptions.ConnectTimeout:
NETWORK_STATUS=False
exceptrequests.exceptions.Timeout:
REQUEST_TIMEOUT=TRUE

5. python3套接字udp設置接受數據超時

Sometimes,you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout.

設定並獲取默認的套接字超時時間。

1.代碼

1 import socket
2
3
4 def test_socket_timeout():
5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6 print("Default socket timeout: %s" % s.gettimeout())
7 # 獲取套接字默認超時時間
8 s.settimeout(100)
9 # 設置超時時間
10 print("Current socket timeout: %s" % s.gettimeout())
11 # 讀取修改後的套接字超時時間
12
13
14 if __name__ == '__main__':
15 test_socket_timeout()
2. AF_INET和SOCK_STREAM解釋

1 # 地址簇
2 # socket.AF_INET IPv4(默認)
3 # socket.AF_INET6 IPv6
4 # socket.AF_UNIX 只能夠用於單一的Unix系統進程間通信
5
6 # socket.SOCK_STREAM(數據流) 提供面向連接的穩定數據傳輸,即TCP/IP協議.多用於資料(如文件)傳送。
3.gettimeout()和settimeout()解釋

1 def gettimeout(self): # real signature unknown; restored from __doc__
2 """
3 gettimeout() -> timeout
4
5 Returns the timeout in seconds (float) associated with socket
6 operations. A timeout of None indicates that timeouts on socket
7 operations are disabled.
8 """
9 return timeout
10
11
12 def settimeout(self, timeout): # real signature unknown; restored from __doc__
13 """
14 settimeout(timeout)
15
16 Set a timeout on socket operations. 'timeout' can be a float,
17 giving in seconds, or None. Setting a timeout of None disables
18 the timeout feature and is equivalent to setblocking(1).
19 Setting a timeout of zero is the same as setblocking(0).
20 """
21 pass
22 # 設置套接字操作的超時期,timeout是一個浮點數,單位是秒。值為None表示沒有超時期。
23 # 一般,超時期應該在剛創建套接字時設置,因為它們可能用於連接的操作(如 client 連接最多等待5s )
4.運行結果

1 Default socket timeout: None
2 Current socket timeout: 100.0

6. python如何設置超時重新運行

python通過subprocess模塊調用系統命令。實際使用中,有一次是命令進入了交互模式,結果web端直接卡死了。
調用時設置一個超時時間,時間用完後自動斷開。
這樣就避免了系統因為調用命令而僵死的問題。

7. python中主線程怎樣捕獲子線程的異常

最近因為別的需求,寫了一個模塊,似乎在這里能用得上:

https://github.com/SakuraSa/ChatProcess


其中的 example.py :

#!/usr/bin/envpython
#coding=utf-8

"""
example
"""

__author__='Rnd495'

fromtimeimportsleep
fromChatProcessimportChatroom


classEcho(Chatroom):
"""
Echo
"""
defresponse(self,data):
ifdata.startswith('sleep'):
sec=float(data[6:])
sleep(sec)
return'wakeupafter%dms'%(sec*1000)
elifdata:
returndata
else:
self.stop()
return'goodbye'


if__name__=='__main__':
,ProcessError

print'process01:'
e=Echo.create_process(lifetime=1).start()
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:0.1'),e.remain
printe.chat(''),e.remain

print''
print'process02:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:1.0'),e.remain
printe.chat(''),e.remain
exceptTimeoutError,error:
print'error:',error

print''
print'process03:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:notanum'),e.remain
printe.chat(''),e.remain
exceptProcessError,error:
print'error:',error


運行結果為:

process01:
Helloworld!0.773000001907
wakeupafter100ms0.549000024796
goodbye0.547000169754

process02:
Helloworld!0.868000030518
error:TimeoutError

process03:
Helloworld!0.868000030518
error:('Erroroccurredonloop',ValueError('couldnotconvertstringtofloat:notanum',))


在其中的 process01 中,主進程捕獲了 超時

在其中的 process02 中,主進程捕獲了 子進程的錯誤


不知道你能不能用得上

8. 怎麼設置python requests的超時時間

方法里有timeout參數,單位是秒:
requests.get(timeout=60)

如果解決了您的問題請採納!
如果未解決請繼續追問!

熱點內容
芒果tv緩存的視頻在哪個文件里 發布:2025-02-07 16:45:05 瀏覽:813
php郵件群發 發布:2025-02-07 16:45:05 瀏覽:612
mysql資料庫基本語句 發布:2025-02-07 16:41:48 瀏覽:250
醫院門禁密碼多少 發布:2025-02-07 16:41:43 瀏覽:527
伺服器遭美國ip攻擊簽名 發布:2025-02-07 16:22:48 瀏覽:546
如何配置二良腌料 發布:2025-02-07 16:11:54 瀏覽:735
資料庫課程設計學生管理系統 發布:2025-02-07 16:11:50 瀏覽:764
美國文化密碼是什麼 發布:2025-02-07 16:07:14 瀏覽:261
安卓手機下雪特效怎麼p 發布:2025-02-07 15:49:30 瀏覽:319
輪胎存儲銘牌 發布:2025-02-07 15:43:38 瀏覽:74