Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Sử dụng Sleep () để mã hóa Bot thời gian hoạt động Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using sleep() to Code a Python Uptime Bot
Bạn đã bao giờ cần phải làm cho chương trình Python của bạn chờ đợi một cái gì đó? Hầu hết thời gian, bạn muốn mã của mình thực thi càng nhanh càng tốt. Nhưng có những lúc để mã của bạn ngủ trong một thời gian thực sự là lợi ích tốt nhất của bạn.
Ví dụ: bạn có thể sử dụng cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 để mô phỏng độ trễ trong chương trình của bạn. Có lẽ bạn cần chờ một tệp để tải lên hoặc tải xuống hoặc cho một đồ họa tải hoặc được vẽ vào màn hình. Bạn thậm chí có thể cần phải tạm dừng giữa các cuộc gọi đến API Web hoặc giữa các truy vấn vào cơ sở dữ liệu. Thêm các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 vào chương trình của bạn có thể giúp đỡ trong từng trường hợp này và nhiều hơn nữa!
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 calls to your program can
help in each of these cases, and many more!
Trong hướng dẫn này, bạn sẽ học cách thêm các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 với:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8
Trang trí
Chủ đề
Async io
Giao diện người dùng đồ họa
Bài viết này dành cho các nhà phát triển trung gian, những người đang tìm cách phát triển kiến thức về Python. Nếu điều đó nghe có vẻ như bạn, thì hãy để bắt đầu!
Thêm cuộc gọi Python $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 với $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
8
Python đã hỗ trợ tích hợp để đưa chương trình của bạn vào giấc ngủ. Mô -đun
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
1 có chức năng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 mà bạn có thể sử dụng để đình chỉ thực thi luồng gọi trong nhiều giây bạn chỉ định.
Ở đây, một ví dụ về cách sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8:
>>>
>>> importtime>>> time.sleep(3)# Sleep for 3 seconds
Nếu bạn chạy mã này trong bảng điều khiển của mình, thì bạn nên trải nghiệm độ trễ trước khi bạn có thể nhập một câu lệnh mới trong bản phát hành.
Bạn có thể kiểm tra thời gian ngủ kéo dài bằng cách sử dụng mô -đun Python từ ____24:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
Tại đây, bạn chạy mô -đun
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4 với tham số
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
6, cho biết
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4 đã bao nhiêu lần để chạy câu lệnh sau đó. Bạn có thể thấy rằng
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4 đã chạy tuyên bố 3 lần và thời gian chạy tốt nhất là 3 giây, đó là những gì được mong đợi.
Số lần mặc định mà
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4 sẽ chạy mã của bạn là một triệu. Nếu bạn đã chạy mã trên với
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
6 mặc định, thì ở mức 3 giây cho mỗi lần lặp, thiết bị đầu cuối của bạn sẽ bị treo trong khoảng 34 ngày! Mô -đun
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4 có một số tùy chọn dòng lệnh khác mà bạn có thể xem trong tài liệu của nó.
Hãy để tạo ra một cái gì đó thực tế hơn một chút. Một quản trị viên hệ thống cần biết khi nào một trong những trang web của họ đi xuống. Bạn muốn có thể kiểm tra mã trạng thái của trang web thường xuyên, nhưng bạn có thể truy vấn máy chủ web liên tục hoặc nó sẽ ảnh hưởng đến hiệu suất. Một cách để thực hiện kiểm tra này là sử dụng cuộc gọi hệ thống Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5:
importtimeimporturllib.requestimporturllib.errordefuptime_bot(url):whileTrue:try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')excepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')else:# Website is upprint(f'{url} is up')time.sleep(60)if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
Ở đây bạn tạo
HTTPError: 404 for http://www.google.com/py
3, lấy một URL làm đối số của nó. Hàm sau đó cố gắng mở URL đó bằng
HTTPError: 404 for http://www.google.com/py
4. Nếu có một
HTTPError: 404 for http://www.google.com/py
5 hoặc
HTTPError: 404 for http://www.google.com/py
6, thì chương trình sẽ bắt nó và in lỗi. (Trong một môi trường trực tiếp, bạn sẽ đăng nhập lỗi và có thể gửi email cho quản trị viên web hoặc quản trị viên hệ thống.)
Nếu không có lỗi xảy ra, thì mã của bạn sẽ in ra rằng tất cả đều tốt. Bất kể điều gì xảy ra, chương trình của bạn sẽ ngủ trong 60 giây. Điều này có nghĩa là bạn chỉ truy cập trang web một lần mỗi phút. URL được sử dụng trong ví dụ này là xấu, do đó, nó sẽ xuất những thứ sau vào bảng điều khiển của bạn một lần mỗi phút:
HTTPError: 404 for http://www.google.com/py
Hãy tiếp tục và cập nhật mã để sử dụng URL tốt đã biết, như
HTTPError: 404 for http://www.google.com/py
7. Sau đó, bạn có thể chạy lại nó để thấy nó hoạt động thành công. Bạn cũng có thể cố gắng cập nhật mã để gửi email hoặc đăng nhập các lỗi. Để biết thêm thông tin về cách thực hiện việc này, hãy xem gửi email với Python và đăng nhập vào Python.
Thêm một cuộc gọi Python $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 với các nhà trang trí
Có những lúc bạn cần thử lại một chức năng đã thất bại. Một trường hợp sử dụng phổ biến cho điều này là khi bạn cần thử lại tải xuống tệp vì máy chủ đang bận. Bạn thường giành chiến thắng muốn đưa ra yêu cầu đến máy chủ quá thường xuyên, vì vậy việc thêm cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 giữa mỗi yêu cầu là mong muốn.
Một trường hợp sử dụng khác mà cá nhân tôi đã trải nghiệm là nơi tôi cần kiểm tra trạng thái của giao diện người dùng trong quá trình kiểm tra tự động. Giao diện người dùng có thể tải nhanh hoặc chậm hơn bình thường, tùy thuộc vào máy tính mà tôi đang chạy thử nghiệm. Điều này có thể thay đổi những gì trên màn hình tại thời điểm hiện tại chương trình của tôi đang xác minh một cái gì đó.
Trong trường hợp này, tôi có thể bảo chương trình ngủ một lúc và sau đó kiểm tra lại mọi thứ một hoặc hai sau. Điều này có thể có nghĩa là sự khác biệt giữa một bài kiểm tra vượt qua và thất bại.
Bạn có thể sử dụng một trình trang trí để thêm một cuộc gọi hệ thống Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 trong một trong những trường hợp này. Nếu bạn không quen thuộc với các nhà trang trí, hoặc nếu bạn muốn đánh vào chúng, thì hãy xem Primer trên các trang trí Python. Hãy nhìn vào một ví dụ:decorator to add a Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 system call in either of these cases. If you’re not familiar with decorators, or if you’d like to brush up on them, then check out
Primer on Python Decorators. Let’s look at an example:
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 là người trang trí của bạn. Nó chấp nhận giá trị
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
2 và số lần nó nên
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
3, mặc định là 3. Bên trong
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 là một hàm khác,
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
5, chấp nhận hàm được trang trí.
Cuối cùng, hàm trong cùng
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
6 chấp nhận các đối số và từ khóa đối số mà bạn chuyển đến hàm được trang trí. Đây là nơi điều kỳ diệu xảy ra! Bạn sử dụng vòng lặp
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
7 để thử lại gọi chức năng. Nếu có một ngoại lệ, thì bạn gọi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8, tăng bộ đếm
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
9 và thử chạy lại chức năng.
Bây giờ viết lại
HTTPError: 404 for http://www.google.com/py
3 để sử dụng bộ trang trí mới của bạn:
@sleep(3)defuptime_bot(url):try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.HTTPErrorexcepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.URLErrorelse:# Website is upprint(f'{url} is up')if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
Tại đây, bạn trang trí
HTTPError: 404 for http://www.google.com/py
3 với
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 trong 3 giây. Bạn cũng đã loại bỏ vòng lặp
importtimeimporturllib.requestimporturllib.errordefsleep(timeout,retry=3):defthe_real_decorator(function):defwrapper(*args,**kwargs):retries=0whileretries<retry:try:value=function(*args,**kwargs)ifvalueisNone:returnexcept:print(f'Sleeping for {timeout} seconds')time.sleep(timeout)retries+=1returnwrapperreturnthe_real_decorator
7 gốc, cũng như cuộc gọi cũ đến
@sleep(3)defuptime_bot(url):try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.HTTPErrorexcepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.URLErrorelse:# Website is upprint(f'{url} is up')if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
4. Các nhà trang trí bây giờ chăm sóc điều này.
Một thay đổi khác mà bạn đã thực hiện là thêm
@sleep(3)defuptime_bot(url):try:conn=urllib.request.urlopen(url)excepturllib.error.HTTPErrorase:# Email admin / logprint(f'HTTPError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.HTTPErrorexcepturllib.error.URLErrorase:# Email admin / logprint(f'URLError: {e.code} for {url}')# Re-raise the exception for the decoratorraiseurllib.error.URLErrorelse:# Website is upprint(f'{url} is up')if__name__=='__main__':url='http://www.google.com/py'uptime_bot(url)
5 bên trong các khối xử lý ngoại lệ. Điều này là để người trang trí sẽ hoạt động đúng. Bạn có thể viết bộ trang trí để xử lý các lỗi này, nhưng vì những ngoại lệ này chỉ áp dụng cho
HTTPError: 404 for http://www.google.com/py
4, bạn có thể tốt hơn là giữ cho người trang trí theo cách của nó. Bằng cách đó, nó sẽ hoạt động với nhiều chức năng khác nhau.
Có một vài cải tiến mà bạn có thể thực hiện cho người trang trí của bạn. Nếu nó hết các thử nghiệm và vẫn thất bại, thì bạn có thể đưa ra nó lại lỗi cuối cùng. Người trang trí cũng sẽ đợi 3 giây sau thất bại cuối cùng, đó có thể là điều bạn không muốn xảy ra. Hãy thử những bài tập này như một bài tập!
Thêm cuộc gọi Python $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 với các chủ đề
Cũng có những lúc bạn có thể muốn thêm một cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 vào một chủ đề. Có lẽ bạn đang chạy một kịch bản di chuyển đối với cơ sở dữ liệu với hàng triệu hồ sơ trong sản xuất. Bạn không muốn gây ra bất kỳ thời gian chết nào, nhưng bạn cũng không muốn chờ đợi lâu hơn mức cần thiết để hoàn thành việc di chuyển, vì vậy bạn quyết định sử dụng các chủ đề.thread. Perhaps you’re running a migration script against a database with millions of records in production. You don’t want to cause any downtime, but you also don’t want to wait longer than necessary to finish the migration, so you decide to use threads.
Để ngăn khách hàng nhận thấy bất kỳ loại chậm nào, mỗi chủ đề cần chạy trong một thời gian ngắn và sau đó ngủ. Có hai cách để làm điều này:
Sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8 như trước đây.
Sử dụng
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
0 từ mô -đun
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
1.
Hãy bắt đầu bằng cách nhìn vào
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8.
Sử dụng $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
8
Cookbook đăng nhập Python cho thấy một ví dụ hay sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8. Mô-đun Python sườn ____ ____65 an toàn cho luồng, do đó, nó hữu ích hơn một chút so với các câu lệnh
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
6 cho bài tập này. Mã sau dựa trên ví dụ này:
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
Tại đây, bạn sử dụng mô -đun Python từ
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
1 để tạo hai luồng. Bạn cũng tạo một đối tượng ghi nhật ký sẽ ghi nhật ký
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
8 vào stdout. Tiếp theo, bạn bắt đầu cả hai luồng và bắt đầu một vòng lặp để đăng nhập từ luồng chính thường xuyên. Bạn sử dụng
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
9 để bắt người dùng nhấn ctrl+c.Ctrl+C.
Hãy thử chạy mã ở trên trong thiết bị đầu cuối của bạn. Bạn sẽ thấy đầu ra tương tự như sau:
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
Khi mỗi luồng chạy và sau đó ngủ, đầu ra ghi nhật ký được in vào bảng điều khiển. Bây giờ bạn đã thử một ví dụ, bạn sẽ có thể sử dụng các khái niệm này trong mã của riêng bạn.
Sử dụng import logging
import threading
import time
def worker(arg):
while not arg["stop"]:
logging.debug("worker thread checking in")
time.sleep(1)
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(relativeCreated)6d %(threadName)s %(message)s"
)
info = {"stop": False}
thread = threading.Thread(target=worker, args=(info,))
thread_two = threading.Thread(target=worker, args=(info,))
thread.start()
thread_two.start()
while True:
try:
logging.debug("Checking in from main thread")
time.sleep(0.75)
except KeyboardInterrupt:
info["stop"] = True
logging.debug('Stopping')
break
thread.join()
thread_two.join()
if __name__ == "__main__":
main()
0
Mô -đun
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
1 cung cấp một
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
2 mà bạn có thể sử dụng như
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8. Tuy nhiên,
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
2 có thêm lợi ích là phản ứng nhanh hơn. Lý do cho điều này là khi sự kiện được thiết lập, chương trình sẽ thoát ra khỏi vòng lặp ngay lập tức. Với
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8, mã của bạn sẽ cần phải chờ cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 để hoàn thành trước khi luồng có thể thoát.
Lý do bạn muốn sử dụng
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
7 ở đây là vì
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
7 không chặn, trong khi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8 bị chặn. Điều này có nghĩa là khi bạn sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8, bạn sẽ chặn luồng chính tiếp tục chạy trong khi chờ đợi cuộc gọi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 kết thúc.
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
7 giải quyết vấn đề này. Bạn có thể đọc thêm về cách tất cả những điều này hoạt động trong tài liệu luồng Python.non-blocking, whereas
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8 is blocking. What this means is that when you use
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8, you’ll block the main thread from continuing to run while it waits for the
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 call to end.
0 Thread-1 worker thread checking in 1 Thread-2 worker thread checking in 1 MainThread Checking in from main thread752 MainThread Checking in from main thread1001 Thread-1 worker thread checking in1001 Thread-2 worker thread checking in1502 MainThread Checking in from main thread2003 Thread-1 worker thread checking in2003 Thread-2 worker thread checking in2253 MainThread Checking in from main thread3005 Thread-1 worker thread checking in3005 MainThread Checking in from main thread3005 Thread-2 worker thread checking in
7 solves this problem. You can read more about how all this works in Python’s
threading documentation.
Tại đây, cách bạn thêm một cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 với
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
0:
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
Trong ví dụ này, bạn tạo
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
5 và chuyển nó sang
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
6. (Nhớ lại rằng trong ví dụ trước, thay vào đó bạn đã chuyển từ điển.) Tiếp theo, bạn thiết lập các vòng lặp của mình để kiểm tra xem
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
7 có được đặt hay không. Nếu nó không, thì mã của bạn sẽ in một tin nhắn và đợi một chút trước khi kiểm tra lại. Để đặt sự kiện, bạn có thể nhấn Ctrl+c. Khi sự kiện được đặt,
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
6 sẽ trở lại và vòng lặp sẽ bị phá vỡ, kết thúc chương trình.Ctrl+C. Once the event is set,
importloggingimportthreadingdefworker(event):whilenotevent.isSet():logging.debug("worker thread checking in")event.wait(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")event=threading.Event()thread=threading.Thread(target=worker,args=(event,))thread_two=threading.Thread(target=worker,args=(event,))thread.start()thread_two.start()whilenotevent.isSet():try:logging.debug("Checking in from main thread")event.wait(0.75)exceptKeyboardInterrupt:event.set()breakif__name__=="__main__":main()
6 will return and the loop will break, ending the program.
Hãy xem xét kỹ hơn về khối mã ở trên. Làm thế nào bạn sẽ vượt qua trong một thời gian ngủ khác nhau cho mỗi chủ đề của công nhân? Bạn có thể hình dung về nó? Hãy tự mình giải quyết bài tập này!
Thêm một cuộc gọi Python $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 với Async IO
Khả năng không đồng bộ đã được thêm vào Python trong bản phát hành 3.4 và bộ tính năng này đã được mở rộng mạnh mẽ kể từ đó. Lập trình không đồng bộ là một loại lập trình song song cho phép bạn chạy nhiều tác vụ cùng một lúc. Khi một nhiệm vụ kết thúc, nó sẽ thông báo cho chủ đề chính.Asynchronous programming is a type of parallel programming that allows you to run multiple tasks at once. When a task finishes, it
will notify the main thread.
0 là một mô -đun cho phép bạn thêm một cuộc gọi python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 không đồng bộ. Nếu bạn không quen thuộc với việc triển khai chương trình không đồng bộ của Python, thì hãy xem Async IO trong Python: một hướng dẫn hoàn chỉnh và đồng thời Python & lập trình song song.
importloggingimportthreadingimporttimedefworker(arg):whilenotarg["stop"]:logging.debug("worker thread checking in")time.sleep(1)defmain():logging.basicConfig(level=logging.DEBUG,format="%(relativeCreated)6d%(threadName)s%(message)s")info={"stop":False}thread=threading.Thread(target=worker,args=(info,))thread_two=threading.Thread(target=worker,args=(info,))thread.start()thread_two.start()whileTrue:try:logging.debug("Checking in from main thread")time.sleep(0.75)exceptKeyboardInterrupt:info["stop"]=Truelogging.debug('Stopping')breakthread.join()thread_two.join()if__name__=="__main__":main()
6.
Dưới đây, một ví dụ hấp dẫn hơn từ phần coroutines và nhiệm vụ của tài liệu
0, Python will run the tasks asynchronously. So, when you run the code above, it should finish in 3 seconds total instead of 6.
Thêm cuộc gọi Python $ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 với GUI
Các ứng dụng dòng lệnh không phải là nơi duy nhất mà bạn có thể cần thêm các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5. Khi bạn tạo giao diện người dùng đồ họa (GUI), thỉnh thoảng bạn sẽ cần thêm sự chậm trễ. Ví dụ: bạn có thể tạo một ứng dụng FTP để tải xuống hàng triệu tệp, nhưng bạn cần thêm một cuộc gọi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 giữa các lô để bạn không sử dụng máy chủ.Graphical User Interface (GUI), you’ll occasionally need to add delays. For example, you might create an FTP application to download millions of files, but you need to add a
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 call between batches so you don’t bog down
the server.
Mã GUI sẽ chạy tất cả việc xử lý và vẽ trong một luồng chính gọi là vòng lặp sự kiện. Nếu bạn sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8 bên trong mã GUI, thì bạn sẽ chặn vòng lặp sự kiện của nó. Từ quan điểm của người dùng, ứng dụng có thể đóng băng. Người dùng đã giành chiến thắng có thể tương tác với ứng dụng của bạn trong khi nó ngủ với phương pháp này. (Trên Windows, bạn thậm chí có thể nhận được cảnh báo về cách ứng dụng của bạn không phản hồi.)event loop. If you use
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8 inside of GUI code, then you’ll block its event loop. From the user’s perspective, the application could appear to freeze. The user won’t be able to interact with your application while it’s sleeping with this method. (On Windows, you might even get an alert about how your application is now unresponsive.)
May mắn thay, có những phương pháp khác bạn có thể sử dụng ngoài
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8. Trong một vài phần tiếp theo, bạn sẽ học cách thêm các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 trong cả Tkinter và Wxpython.
Ngủ trong tkinter
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
12 là một phần của thư viện tiêu chuẩn Python. Nó có thể không có sẵn cho bạn nếu bạn sử dụng phiên bản Python được cài đặt sẵn trên Linux hoặc Mac. Nếu bạn nhận được
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
13, thì bạn sẽ cần phải xem xét cách thêm nó vào hệ thống của bạn. Nhưng nếu bạn tự cài đặt Python, thì
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
12 đã có sẵn.
Bạn sẽ bắt đầu bằng cách xem xét một ví dụ sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8. Chạy mã này để xem điều gì xảy ra khi bạn thêm Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 Gọi sai cách:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
2
Khi bạn đã chạy mã, nhấn nút trong GUI của bạn. Nút sẽ dính xuống trong ba giây khi chờ
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 kết thúc. Nếu ứng dụng có các nút khác, thì bạn sẽ không thể nhấp vào chúng. Bạn có thể đóng ứng dụng trong khi nó ngủ, vì nó có thể phản ứng với sự kiện gần gũi.
Để có được
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
12 để ngủ đúng cách, bạn sẽ cần sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
19:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
3
Tại đây, bạn tạo một ứng dụng rộng 400 pixel cao 400 pixel. Nó không có widget trên đó. Tất cả nó sẽ làm là hiển thị một khung. Sau đó, bạn gọi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
20 trong đó
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
21 là một tham chiếu đến đối tượng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
22.
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
19 có hai đối số:
Số lượng mili giây để ngủ
Phương pháp gọi khi giấc ngủ kết thúc
Trong trường hợp này, ứng dụng của bạn sẽ in một chuỗi vào stdout sau 3 giây. Bạn có thể nghĩ
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
19 là phiên bản
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
12 của
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
8, nhưng nó cũng thêm khả năng gọi một chức năng sau khi ngủ kết thúc.
Bạn có thể sử dụng chức năng này để cải thiện trải nghiệm người dùng. Bằng cách thêm một cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5, bạn có thể làm cho ứng dụng xuất hiện để tải nhanh hơn và sau đó bắt đầu một quá trình chạy dài hơn sau khi nó lên. Bằng cách đó, người dùng đã giành chiến thắng phải chờ ứng dụng mở.
Ngủ trong wxpython
Có hai sự khác biệt chính giữa Wxpython và Tkinter:
Wxpython có nhiều vật dụng hơn.
Wxpython nhằm mục đích nhìn và cảm nhận bản địa trên tất cả các nền tảng.
Khung Wxpython không được bao gồm trong Python, vì vậy bạn sẽ cần phải tự cài đặt. Nếu bạn không quen thuộc với Wxpython, thì hãy xem cách xây dựng ứng dụng GUI Python với WxPython.
Trong WxPython, bạn có thể sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
28 để thêm cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
4
Tại đây, bạn phân lớp
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
30 trực tiếp và sau đó gọi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
28. Hàm này có các tham số giống như Tkinter từ
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
19:
Số lượng mili giây để ngủ
Phương pháp gọi khi giấc ngủ kết thúc
Khi bạn chạy mã này, bạn sẽ thấy một cửa sổ trống nhỏ xuất hiện mà không có bất kỳ tiện ích nào. Sau 4 giây, bạn sẽ thấy chuỗi
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
33 được in vào stdout.
Một trong những lợi ích của việc sử dụng
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
28 là nó an toàn cho chủ đề. Bạn có thể sử dụng phương thức này từ bên trong một luồng để gọi một hàm mà trong ứng dụng WxPython chính.
Sự kết luận
Với hướng dẫn này, bạn đã có được một kỹ thuật mới có giá trị để thêm vào hộp công cụ Python của bạn! Bạn biết làm thế nào để thêm sự chậm trễ để tăng tốc ứng dụng của bạn và ngăn chúng sử dụng tài nguyên hệ thống. Bạn thậm chí có thể sử dụng các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 để giúp mã GUI của bạn vẽ lại hiệu quả hơn. Điều này sẽ làm cho trải nghiệm người dùng tốt hơn nhiều cho khách hàng của bạn!
Tóm lại, bạn đã học cách thêm các cuộc gọi Python
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
5 với các công cụ sau:
$ python3 -m timeit -n 3"import time; time.sleep(3)"3 loops, best of 5: 3 sec per loop
Bây giờ bạn có thể lấy những gì bạn đã học và bắt đầu đặt mã của bạn vào giấc ngủ!
Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Sử dụng Sleep () để mã hóa Bot thời gian hoạt động Python This tutorial has a related video course
created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using sleep() to Code a Python Uptime Bot
Làm thế nào để bạn làm một độ trễ 1 giây trong Python?
Để thêm độ trễ thời gian trong quá trình thực hiện, chúng tôi sử dụng hàm Sleep () giữa hai câu giữa chúng tôi muốn độ trễ.Trong hàm ngủ () chuyển tham số dưới dạng giá trị số nguyên hoặc float.Chạy chương trình.Lưu ý độ trễ trong thời gian thực hiện.use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value. Run the program. Notice the delay in the execution time.
Có một lệnh chờ trong Python?
Hàm chờ () được xác định trong hai mô -đun riêng biệt trong Python.Lớp sự kiện của mô -đun luồng chứa phương thức Wait () đình chỉ thực thi của luồng hiện tại trong khi sự kiện được thực thi hoặc hoàn thành.. The threading module's event class contains a wait() method that suspends the current thread's execution while the event is executed or completed.
Làm thế nào để bạn trì hoãn một lệnh trong Python?
Hàm Python Sleep () sẽ tạm dừng mã Python hoặc trì hoãn việc thực hiện chương trình trong số giây được đưa ra làm đầu vào cho giấc ngủ ().Hàm giấc ngủ () là một phần của mô -đun thời gian Python.Bạn có thể sử dụng chức năng giấc ngủ Python khi bạn muốn tạm dừng việc thực thi mã của mình. will pause Python code or delay the execution of program for the number of seconds given as input to sleep(). The sleep() function is part of the Python time module. You can make use of Python sleep function when you want to temporarily halt the execution of your code.