Hướng dẫn how do you input wait in python? - làm thế nào để bạn nhập đợi trong python?

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

Show

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

import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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:

>>>

>>> import time
>>> 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

import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(f'{url} is up')
        time.sleep(60)

if __name__ == '__main__':
    url = 'http://www.google.com/py'
    uptime_bot(url)
4 với tham số
import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(f'{url} is up')
        time.sleep(60)

if __name__ == '__main__':
    url = 'http://www.google.com/py'
    uptime_bot(url)
6, cho biết
import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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
import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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à

import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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
import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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
import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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:

import time
import urllib.request
import urllib.error

def uptime_bot(url):
    while True:
        try:
            conn = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            # Email admin / log
            print(f'HTTPError: {e.code} for {url}')
        except urllib.error.URLError as e:
            # Email admin / log
            print(f'URLError: {e.code} for {url}')
        else:
            # Website is up
            print(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:

import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_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ị
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_real_decorator
2 và số lần nó nên
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_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,
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_real_decorator
5, chấp nhận hàm được trang trí.

Cuối cùng, hàm trong cùng

import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_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
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_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
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_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)
def uptime_bot(url):
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Email admin / log
        print(f'HTTPError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.HTTPError
    except urllib.error.URLError as e:
        # Email admin / log
        print(f'URLError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.URLError
    else:
        # Website is up
        print(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
import time
import urllib.request
import urllib.error

def sleep(timeout, retry=3):
    def the_real_decorator(function):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < retry:
                try:
                    value = function(*args, **kwargs)
                    if value is None:
                        return
                except:
                    print(f'Sleeping for {timeout} seconds')
                    time.sleep(timeout)
                    retries += 1
        return wrapper
    return the_real_decorator
7 gốc, cũng như cuộc gọi cũ đến
@sleep(3)
def uptime_bot(url):
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Email admin / log
        print(f'HTTPError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.HTTPError
    except urllib.error.URLError as e:
        # Email admin / log
        print(f'URLError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.URLError
    else:
        # Website is up
        print(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)
def uptime_bot(url):
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Email admin / log
        print(f'HTTPError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.HTTPError
    except urllib.error.URLError as e:
        # Email admin / log
        print(f'URLError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.URLError
    else:
        # Website is up
        print(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:

  1. 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.
  2. 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 từ mô -đun
    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()
    
    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
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()
6 cho bài tập này. Mã sau dựa trên ví dụ này:

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()

Tại đây, bạn sử dụng mô -đun Python từ

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()
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ý
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()
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
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()
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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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

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()
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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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 thread
752 MainThread Checking in from main thread
1001 Thread-1 worker thread checking in
1001 Thread-2 worker thread checking in
1502 MainThread Checking in from main thread
2003 Thread-1 worker thread checking in
2003 Thread-2 worker thread checking in
2253 MainThread Checking in from main thread
3005 Thread-1 worker thread checking in
3005 MainThread Checking in from main thread
3005 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
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:

import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __name__ == "__main__":
    main()

Trong ví dụ này, bạn tạo

import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __name__ == "__main__":
    main()
5 và chuyển nó sang
import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __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
import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __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,
import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __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,
import logging
import threading

def worker(event):
    while not event.isSet():
        logging.debug("worker thread checking in")
        event.wait(1)

def main():
    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()

    while not event.isSet():
        try:
            logging.debug("Checking in from main thread")
            event.wait(0.75)
        except KeyboardInterrupt:
            event.set()
            break

if __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.

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
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.

Ở đây, một ví dụ từ tài liệu riêng của Python:

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())

Trong ví dụ này, bạn chạy

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
2 và ngủ trong một giây giữa hai cuộc gọi
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()
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

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
0:

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
0

Trong mã này, bạn tạo một công nhân tên là

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
5 mất số giây đến
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
6 và
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
7 để in ra. Sau đó, bạn sử dụng từ khóa Python từ ____998 để chờ mã
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
5 chạy.
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
8 được yêu cầu ở đây vì
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
5 đã được đánh dấu là hàm
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
02, vì vậy bạn có thể gọi nó giống như bạn sẽ là một hàm bình thường.

Khi bạn chạy mã này, chương trình của bạn sẽ thực thi

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
8 3 lần. Mã sẽ chờ 1, 2 và 3 giây, trong tổng thời gian chờ là 6 giây. Bạn cũng có thể viết lại mã để các tác vụ chạy song song:

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
1

Bây giờ bạn sử dụng khái niệm về các nhiệm vụ, mà bạn có thể thực hiện với

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
04. Khi bạn sử dụng các nhiệm vụ trong
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
0, Python sẽ chạy các nhiệm vụ không đồng bộ. Vì vậy, khi bạn chạy mã ở trên, nó sẽ hoàn thành tổng số 3 giây thay vì 6.tasks, which you can make with
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
04. When you use tasks in
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
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ố:

  1. Số lượng mili giây để ngủ
  2. 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:

  1. Wxpython có nhiều vật dụng hơn.
  2. 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:

  1. Số lượng mili giây để ngủ
  2. 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
    
    8
  • Trang trí
  • Chủ đề
  • import asyncio
    
    async def main():
        print('Hello ...')
        await asyncio.sleep(1)
        print('... World!')
    
    # Python 3.7+
    asyncio.run(main())
    
    0
  • Tkinter
  • Wxpython

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