本文目錄一覽:
讓Python腳本暫停執行的幾種方法求解
參考文檔原文:
Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate thesleep()following execution of that signal』s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.大意:讓程序執行暫停指定的秒數,參數可以是浮點型以指定精確的時間,但是程序真正暫停的時間可能長於請求的時間也可能短於暫停的時間。
2. raw_input( )
通過等待輸入來讓程序暫停
3. os.system(“pause”)
通過執行操作系統的命令來讓程序暫停,該函數是通過實現標準C函數system( )來實現的。
Python2.4新加入了subprocess模塊,而且官方建議使用改模塊替換os.system所以,也可以這樣寫:
求噴!求補充!
如何中斷python的執行
在Python3中已經有很大一部分語句與Python2不互通了,運行暫停的方法也有所不同。
1、input();
這種方法不用包含模塊,因此這也是最常用的一種暫停手段。
Python2中的raw_input()和input()語句在Python3中已經被合併到input()中。
2、os.system(pause);
這種方法需要包含os模塊(import os),在windows下IDLE運行會彈出cmd命令行,
進行暫停操作,直接運行.py文件會直接在命令行中暫停。
3、time.sleep(second);
這種方法需要包含time模塊(import time),second是自定義的時間長短,根據實際情況,可能會發生上下浮動。
推薦學習《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)
擴展資料
有時當一個條件成立的情況下,需要終止程序,可以使用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)。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/180078.html