Trăn ngủ bao nhiêu tiếng một ngày?

Ở đây mỗi vòng tròn bằng 24 giờ. Có 12 cung trong hình tròn. Vì vậy, mỗi khu vực bằng 2 giờ

Show

Theo phần tô đậm, bò ngủ 4 tiếng

Trăn ngủ bao nhiêu tiếng một ngày?
, trăn ngủ 18 tiếng
Trăn ngủ bao nhiêu tiếng một ngày?
, hươu cao cổ ngủ 2 tiếng (
Trăn ngủ bao nhiêu tiếng một ngày?
) and cat sleeps for 12 hours (
Trăn ngủ bao nhiêu tiếng một ngày?
).

Bạn đã bao giờ cần làm cho chương trình Python của mình chờ một thứ gì đó chưa? . 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 lệnh 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 mình. Có lẽ bạn cần đợi tệp tải lên hoặc tải xuống hoặc để đồ họa tải hoặc được vẽ lên màn hình. Bạn thậm chí có thể cần tạm dừng giữa các cuộc gọi tới API web hoặc giữa các truy vấn tới cơ sở dữ liệu. Thêm lệnh 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ể hữu ích trong từng trường hợp này và nhiều trường hợp khác

Trong hướng dẫn này, bạn sẽ học cách thêm lệnh 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
  • người trang trí
  • chủ đề
  • IO không đồng bộ
  • 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 cấp đang tìm cách nâng cao kiến ​​thức về Python. Nếu điều đó nghe có vẻ giống bạn, thì hãy bắt đầu

Tiền thưởng miễn phí. Nhận hướng dẫn miễn phí "Sức mạnh của Trình trang trí Python" cho bạn thấy ba mẫu và kỹ thuật trang trí nâng cao mà bạn có thể sử dụng để viết cho các chương trình Pythonic sạch hơn và nhiều hơ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 $ python3 -m timeit -n 3 "import time; time.sleep(3)" 3 loops, best of 5: 3 sec per loop 8

Python có hỗ trợ tích hợp để đưa chương trình của bạn vào chế độ 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ó một chức năng mà bạn có thể sử dụng để tạm dừng thực thi chuỗi cuộc gọi trong bao nhiêu giây mà bạn chỉ định

Đây là 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 sẽ gặp phải sự chậm trễ trước khi có thể nhập câu lệnh mới trong REPL

Ghi chú. Trong Trăn 3. 5, các nhà phát triển cốt lõi đã thay đổi hành vi của

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
8 một chú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 mới sẽ kéo dài ít nhất số giây bạn đã chỉ định, ngay cả khi giấc ngủ bị gián đoạn bởi một tín hiệu. Tuy nhiên, điều này không áp dụng nếu chính tín hiệu đưa ra một ngoại lệ

Bạn có thể kiểm tra thời gian ngủ kéo dài bằng cách sử dụ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)
6 của Python

$ 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)
6 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)
8, 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)
6 sẽ chạy câu lệnh theo sau bao nhiêu lần. 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)
6 đã chạy câu lệnh 3 lần và thời gian chạy tốt nhất là 3 giây, đó là điều đượ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)
6 sẽ chạy mã của bạn là một triệu. Nếu bạn chạy đoạn mã trên với giá trị mặc định là
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)
8, thì cứ sau 3 giây cho mỗi lần lặp lại, 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)
6 có một số tùy chọn dòng lệnh khác mà bạn có thể kiểm tra trong phần của nó.

Hãy tạo ra một cái gì đó thực tế hơn một chút. Quản trị viên hệ thống cần biết khi một trong các trang web của họ ngừng hoạt độ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 không thể truy vấn máy chủ web liên tục nếu không sẽ ảnh hưởng đến hiệu suất. Một cách để thực hiện việc kiểm tra này là sử dụng lệnh gọi hệ thống

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

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
5, lấy một URL làm đối số. Sau đó, chức năng sẽ cố gắng mở URL đó bằng
HTTPError: 404 for http://www.google.com/py
6. Nếu có một
HTTPError: 404 for http://www.google.com/py
7 hoặc
HTTPError: 404 for http://www.google.com/py
8, thì chương trình sẽ bắt nó và in ra lỗi. (Trong môi trường trực tiếp, bạn sẽ ghi lại lỗi và có thể gửi email tới 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 in ra rằng tất cả đều ổn. 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 không hợp lệ, do đó, nó sẽ xuất nội dung sau vào bảng điều khiển của bạn mỗi phút một lần

HTTPError: 404 for http://www.google.com/py

Hãy tiếp tục và cập nhật mã để sử dụng một URL tốt đã biết, chẳng hạn như

HTTPError: 404 for http://www.google.com/py
9. Sau đó, bạn có thể chạy lại nó để xem nó hoạt động thành công. Bạn cũng có thể thử cập nhật mã để gửi email hoặc ghi nhật ký 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 bằng Python và Đăng nhập bằng Python

Loại bỏ các quảng cáo

Thêm một cuộc gọi ________0____5 Python với Decorators

Có những lúc bạn cần thử lại một chức năng bị lỗ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ử tải xuống lại tệp vì máy chủ đang bận. Bạn thường không muốn gửi yêu cầu đến máy chủ quá thường xuyên, vì vậy nên thêm một lệnh 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

Một trường hợp sử dụng khác mà cá nhân tôi đã trải nghiệm là khi 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 hơn 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 trên đó. Điều này có thể thay đổi nội dung trên màn hình tại thời điểm chương trình của tôi đang xác minh điều gì đó

Trong trường hợp này, tôi có thể yêu cầu chương trình ngủ trong giây lát và sau đó kiểm tra lại mọi thứ sau một hoặc hai giây. Điều này có thể có nghĩa là sự khác biệt giữa bài kiểm tra đạt và trượt

Bạn có thể sử dụng một trình trang trí để thêm lệnh 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 hai trường hợp này. Nếu bạn không quen thuộc với các công cụ trang trí hoặc nếu bạn muốn tìm hiểu về chúng, thì hãy xem Primer on Python Decorators. Hãy xem một ví dụ

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 một 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
4 và số lần nó phải là
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, 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 chức năng 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
7, chấp nhận chức năng 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
8 chấp nhận các đối số và đối số từ khóa mà bạn chuyển đến hàm được trang trí. Đây là nơi phép mà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
9 để thử gọi lại hàm. Nếu có 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
@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)
1 và thử chạy lại chức năng

Bây giờ hãy viết lại

HTTPError: 404 for http://www.google.com/py
5 để sử dụng trình 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)

Ở đây, bạn trang trí

HTTPError: 404 for http://www.google.com/py
5 bằng một
$ 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
9 ban đầu, cũng như lệnh gọi cũ tới
@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)
6. Người trang trí bây giờ sẽ chăm sóc điều này

Một thay đổi khác mà bạn đã thực hiện là thêm một

@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)
7 bên trong các khối xử lý ngoại lệ. Điều này là để trang trí sẽ hoạt động bình thường. Bạn có thể viết trình trang trí để xử lý những 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
6, tốt hơn hết là bạn nên giữ nguyên trình trang trí đó. Bằng cách đó, nó sẽ hoạt động với nhiều chức năng hơn

Ghi chú. Nếu bạn muốn tìm hiểu về xử lý ngoại lệ trong Python, thì hãy xem Python Exceptions. Một lời giới thiệu

Có một số cải tiến mà bạn có thể thực hiện đối với người trang trí của mình. Nếu hết lần thử lại mà vẫn bị lỗi thì bạn có thể cho nó báo lại lỗi lần trước. Người trang trí cũng sẽ đợi 3 giây sau lần thất bại cuối cùng, đây có thể là điều bạn không muốn xảy ra. Hãy thử những điều này như một bài tập

Thêm một cuộc gọi ________0____5 Python với chủ đề

Cũng có những lúc bạn có thể muốn thêm lệnh 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 chuỗi. Có lẽ bạn đang chạy tập lệnh di chuyển đối với cơ sở dữ liệu có hàng triệu bản ghi đang được 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 đợi lâu hơn mức cần thiết để hoàn tất quá trình di chuyển, vì vậy bạn quyết định sử dụng chuỗi

Ghi chú. Chủ đề là một phương pháp thực hiện đồng thời trong Python. Bạn có thể chạy nhiều luồng cùng một lúc để tăng thông lượng cho ứng dụng của mình. Nếu bạn không quen thuộc với các luồng trong Python, thì hãy xem phần Giới thiệu về luồng trong Python

Để ngăn khách hàng nhận thấy bất kỳ loại chậm nào, mỗi luồng cần chạy trong một khoảng thời gian ngắn rồi 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()
    
    2 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()
    
    3

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

Loại bỏ các quảng cáo

Sử dụng $ python3 -m timeit -n 3 "import time; time.sleep(3)" 3 loops, best of 5: 3 sec per loop 8

Python hiển thị 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
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()
7 của Python an toàn cho luồng, vì vậy 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()
8 cho bài tập này. Đoạn 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()

Ở đây, bạn sử dụng 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()
3 của Python để 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ý
 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
0 vào thiết bị xuất chuẩn. Tiếp theo, bạn bắt đầu cả hai luồng và thường xuyên bắt đầu một vòng lặp để ghi nhật ký từ luồng chính. Bạ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
1 để bắt người dùng nhấn 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 ra bàn đ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 mình

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

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()
3 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
4 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
4 có thêm lợi ích là phản ứng nhanh hơn. Lý do 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 đợi lệnh gọi Python
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 kết thúc 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
9 ở đâ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
9 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 đang 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 đợ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
9 giải quyết vấn đề này. Bạn có thể đọc thêm về cách tất cả những thứ này hoạt động trong Python's

Đây là 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()
2

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()
7 và chuyển nó cho
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()
8. (Nhớ lại rằng trong ví dụ trước, bạn đã chuyển một 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()
9 có được đặt hay không. Nếu không, mã của bạn sẽ in một thông báo 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 . Sau khi sự kiện được thiết lập,
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()
8 sẽ quay trở lại và vòng lặp sẽ bị ngắt, kết thúc chương trình.

Ghi chú. Nếu bạn muốn tìm hiểu thêm về từ điển, hãy xem Dictionaries in Python

Hãy xem xét kỹ hơn khối mã ở trên. Làm cách nào để bạn chuyển thời gian ngủ khác nhau cho từng luồng công nhân?

Thêm một cuộc gọi ________0____5 Python với Async IO

Khả năng không đồng bộ đã được thêm vào Python trong 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 tác vụ kết thúc, nó sẽ thông báo cho luồng chính

import asyncio

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

# Python 3.7+
asyncio.run(main())
2 là một mô-đun cho phép bạn thêm lệnh 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 với việc triển khai lập trình không đồng bộ của Python, thì hãy xem Async IO trong Python. Hướng dẫn hoàn chỉnh và Lập trình song song & đồng thời Python

Đây là 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())
4 và để nó 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()
8

Đây là một ví dụ hấp dẫn hơn từ phần Coroutines và Tasks 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())
2

$ 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 có tên là

import asyncio

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

# Python 3.7+
asyncio.run(main())
7, mất số giây để in ra
import asyncio

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

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

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

# Python 3.7+
asyncio.run(main())
9. Sau đó, bạn sử dụng từ khóa
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
00 của Python để đợi mã
import asyncio

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

# Python 3.7+
asyncio.run(main())
7 chạy.
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
00 đượ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())
7 đã được đánh dấu là một hàm
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
04, vì vậy bạn không thể gọi nó như 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

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
00 3 lần. Mã sẽ đợi trong 1, 2 và 3 giây, tổng thời gian chờ là 6 giây. Bạn cũng có thể viết lại code để các task 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 đang sử dụng khái niệm 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
06. Khi bạn sử dụng các tác vụ trong
import asyncio

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

# Python 3.7+
asyncio.run(main())
2, Python sẽ chạy các tác vụ không đồng bộ. Vì vậy, khi bạn chạy mã ở trên, nó sẽ hoàn thành trong tổng cộng 3 giây thay vì 6

Loại bỏ các quảng cáo

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 Python bằng 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 lệnh gọi

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 Python. Khi bạn tạo Giao diện người dùng đồ họa (GUI), đôi khi bạn sẽ cần thêm độ trễ. Ví dụ: bạn có thể tạo ứng dụng FTP để tải xuống hàng triệu tệp, nhưng bạn cần thêm lệnh 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 đợt để không làm chậm máy chủ

Mã GUI sẽ chạy tất cả quá trình xử lý và vẽ của nó trong một luồng chính được 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ể bị đóng băng. Người dùng sẽ không thể tương tác với ứng dụng của bạn khi nó đang 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ề việc ứng dụng của bạn hiện không phản hồi. )

May mắn thay, có những phương pháp khác mà 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ẽ tìm hiểu cách thêm lệnh 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ủ ở Tkinter

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
14 là một phần của thư viện chuẩn Python. Nó có thể không khả dụng cho bạn nếu bạn đang 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
15, thì bạn sẽ cần xem xét cách thêm nó vào hệ thống của mình. Nhưng nếu bạn tự cài Python thì chắc đã có sẵn
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
14

Bạn sẽ bắt đầu bằng cách xem 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ì sẽ xảy ra khi bạn thêm lệnh gọi Python
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 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ã, hãy 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ũng không thể đóng ứng dụng khi nó đang ngủ vì nó không thể phản hồi sự kiện đóng

Để

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
14 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
21

$ 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ó vật dụng nào trên đó. Tất cả những gì 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
22 trong đó
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
23 là 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
24.
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
21 có hai đối số

  1. Số mili giây để ngủ
  2. Phương thức gọi khi quá trình 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 ra thiết bị xuất chuẩn sau 3 giây. Bạn có thể coi

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
21 là phiên bản
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
14 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 bổ sung khả năng gọi một hàm sau khi quá trình 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 lệnh 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 tải nhanh hơn và sau đó bắt đầu một số quy trình chạy lâu hơn sau khi hoàn thành. Bằng cách đó, người dùng sẽ không phải đợi ứng dụng mở

Ngủ trong wxPython

Có hai điểm khác biệt chính giữa wxPython và Tkinter

  1. wxPython có nhiều widget hơn
  2. wxPython hướng đến giao diện tự nhiên 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ó. Nếu bạn chưa quen với wxPython, 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
30 để thêm lệnh 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

Ở đây, bạn phân lớp trực tiếp

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
32 rồi gọi
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
30. Hàm này có cùng tham số như Tkinter's
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
21

  1. Số mili giây để ngủ
  2. Phương thức gọi khi quá trình 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ỳ vật dụng 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
35 được in ra thiết bị xuất chuẩn

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
30 là nó an toàn cho luồng. Bạn có thể sử dụng phương thức này từ trong một luồng để gọi một hàm trong ứng dụng wxPython chính

Loại bỏ các quảng cáo

Phần 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 mình. Bạn biết cách thêm độ trễ để tăng tốc ứng dụng của mình và ngăn chúng sử dụng hết tài nguyên hệ thống. Bạn thậm chí có thể sử dụng lệnh 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 lệnh gọi

$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
5 Python bằng 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
  • người trang trí
  • chủ đề
  • import asyncio
    
    async def main():
        print('Hello ...')
        await asyncio.sleep(1)
        print('.. World!')
    
    # Python 3.7+
    asyncio.run(main())
    
    2
  • 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 mình vào trạng thái ngủ

Đánh dấu là đã hoàn thành

Xem ngay Hướng dẫn này có một khóa học video liên quan do nhóm Real Python tạo. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn. Sử dụng chế độ ngủ() để mã hóa Bot thời gian hoạt động của Python

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Trăn ngủ bao nhiêu tiếng một ngày?

Gửi cho tôi thủ thuật Python »

Giới thiệu về Mike Driscoll

Trăn ngủ bao nhiêu tiếng một ngày?
Trăn ngủ bao nhiêu tiếng một ngày?

Mike đã lập trình bằng Python hơn một thập kỷ và thích viết về Python

» Thông tin thêm về Mike


Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Trăn ngủ bao nhiêu tiếng một ngày?

Aldren

Trăn ngủ bao nhiêu tiếng một ngày?

Geir Arne

Trăn ngủ bao nhiêu tiếng một ngày?

Jaya

Trăn ngủ bao nhiêu tiếng một ngày?

Jon

Trăn ngủ bao nhiêu tiếng một ngày?

Joanna

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Một con trăn ngủ bao nhiêu?

Mùa có thể đóng một vai trò trong thói quen ngủ của rắn. Hầu hết rắn dành khoảng 16 giờ mỗi ngày để ngủ.

Con vật nào ngủ 18 đến 20 giờ một ngày?

Koalas (Phascolartos cinereus) thực sự là một Snorlax ngoài đời thực. Những thú có túi này có thể ngủ từ 18 đến 22 giờ mỗi ngày. Điều này phần lớn là do chế độ ăn uống của họ.

Con khỉ ngủ mấy tiếng?

Con người ngủ ít hơn bất kỳ loài vượn, khỉ hay vượn cáo nào mà các nhà khoa học đã nghiên cứu. Tinh tinh ngủ khoảng 9. 5 giờ trong mỗi 24 giờ. Bông me ngủ khoảng 13. Về mặt kỹ thuật, khỉ ba sọc là loài sống về đêm, mặc dù thực sự chúng hầu như không bao giờ thức — chúng ngủ 17 giờ một ngày .

Con vật nào ngủ 7 tiếng một ngày?

Bản tóm tắt