python線程暫停
Ⅰ 求助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). 不會出現程序的文件操作符超出上限, 資料庫連接未釋放等尷尬的情況.
Ⅱ python怎麼讓進程暫停
加個阻塞,條件ok後在繼續,可以用input()、多線程、多進程、協程等都可以。
Ⅲ python 暫停,繼續線程
Python3, 使用 Thread 對象的 Lock 和 Rlock 可以實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對於那些需要每次只允許一個線程操作的數據,可以將其操作放到 acquire 和 release 方法之間。
Ⅳ Python 如何強制中止線程
Python用sleep停止一個線程的運行,而不影響主線程的運行,案例代碼如下:
from threading import *import time class MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(2) def stop (self): print 'I am stopping it...' self.ifdo = False; tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()
Ⅳ python 暫停幾秒執行下一步、
在代碼開頭引入time模塊:import time
在需要延時的地方加入語句:time.sleep(1)
(括弧中的1意為停頓1秒,想停頓時間更長可以換數字)
舉例:
import time
print '11'
time.sleep(10)
print '22'
先列印11,等待10秒後,列印22。
(5)python線程暫停擴展閱讀:
文件執行
1、用 notepad++ 或 Sublime Text,甚至 寫字本創建一個文件。
2、比如:print('Hello world!')
3、保存為 helloworld.py,一定要選或寫後綴名 .py 。
4、進入cmd命令行,切換(cd)到保存文件的目錄,執行 python helloworld.py,文件名前的python表示調用python解釋器執行文件。
Ⅵ Python中如何在一段時間後停止程序
用到threading的Timer,也類似單片機那樣子,在中斷程序中再重置定時器,設置中斷,python實例代碼如下:
import threading
import time
def change_user():
print('這是中斷,切換賬號')
t = threading.Timer(3, change_user)
t.start()
#每過3秒切換一次賬號
t = threading.Timer(3, change_user)
t.start()
while True:
print('我在爬數據')
time.sleep(1)
(6)python線程暫停擴展閱讀
有時當一個條件成立的情況下,需要終止程序,可以使用sys.exit()退出程序。sys.exit()會引發一個異常:
1、如果這個異常沒有被捕獲,那麼python編譯器將會退出,後面的程序將不會執行。
2、如果這個異常被捕獲(try...except...finally),捕獲這個異常可以做一些額外的清理工作,後面的程序還會繼續執行。
註:0為正常退出,其他數值(1-127)為不正常,可拋異常事件供捕獲。另一種終止程序的方法os._exit()
一般情況下使用sys.exit()即可,一般在fork出來的子進程中使用os._exit()
採用sys.exit(0)正常終止程序,程序終止後shell運行不受影響。
採用os._exit(0)關閉整個shell,調用sys._exit(0)後整個shell都重啟了(RESTART Shell)。
Ⅶ python里如何終止線程 比如線程里調用os.system('adb logcat')這個是不會停止的
如果直接終止線程不清楚,要不曲線下,新開啟一個進程,再得到這個進程id,然後幹掉這個進程
import
multiprocessing
def
NewProcess():
global
id
id=os.getpid()
os.system('adb
logcat')
NP=multiporcess.Process(target=one
function,args=())
NP.start()
os.kill(id,9)
Ⅷ Python中怎麼在終止一個線程的同時終止另外一個線程
設置一個全局變數,初值為False
設置鍵盤監聽事件,當監測到特定按鍵時,將全局變數的值修改為True
在每個子線程中,循環檢測全局變數的值,當檢測到值為True時退出線程函數。
Ⅸ python 在線程函數中如何實現線程的暫停、恢復和終止
我們都知道python中可以是threading模塊實現多線程, 但是模塊並沒有提供暫停, 恢復和停止線程的方法, 一旦線程對象調用start方法後, 只能等到對應的方法函數運行完畢. 也就是說一旦start後, 線程就屬於失控狀態. 不過, 我們可以自己實現這些. 一般的方法就是循環地判斷一個標志位, 一旦標志位到達到預定的值, 就退出循環. 這樣就能做到退出線程了. 但暫停和恢復線程就有點難了, 我一直也不清除有什麼好的方法
Ⅹ Python里如何終止一個線程
Python用sleep停止一個線程的運行,而不影響主線程的運行,案例代碼如下:
fromthreadingimport*
importtime
classMyThread(Thread):
defrun(self):
self.ifdo=True;
whileself.ifdo:
print'Iamrunning...'
time.sleep(2)
defstop(self):
print'Iamstoppingit...'
self.ifdo=False;
tr=MyThread()
tr.setDaemon(True)
tr.start()
print'Iwillstopit...'
time.sleep(5)
tr.stop()
tr.join()