我遇到了一些我無法解決且沒有提供解釋的代碼。我努力了!該代碼分為兩部分,并運行計算機健康檢查。在第二個塊中,“如果不是”行是什么意思?(我不熟悉以這種方式使用函式名)。評論顯示了它的作用,但我對它的作業原理很感興趣。在同一行,括號中的斜線是什么意思?
#!/usr/bin/env python3
import requests
import socket
def check_localhost():
localhost = socket.gethostbyname('localhost')
return localhost == "127.0.0.1"
def check_connectivity():
request = requests.get("http://www.google.com")
return request == 200
#!/usr/bin/env python3
from network import *
import shutil
import psutil
def check_disk_usage(disk):
"""Verifies that there's enough free space on disk"""
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
"""Verifies that there's enough unused CPU"""
usage = psutil.cpu_percent(1)
return usage < 75
# If there's not enough disk, or not enough CPU, print an error
if not check_disk_usage('/') or not check_cpu_usage():
print("ERROR!")
elif check_localhost() and check_connectivity():
print("Everything ok")
else:
print("Network checks failed")
uj5u.com熱心網友回復:
not在 Python 中相當于!在其他語言中;這是一個否定詞。如果以下陳述句不為 true ,則回傳true ,否則回傳 false 。
猜測一下/,括號中的指的是 Unix 檔案系統中的根目錄。
所以那行是說,“如果 root 所在的磁盤空間不足,或者 cpu 不足,則列印錯誤。” 這兩個函式check_disk_usage(folder)都check_cpu_usage()回傳布林值true(表示OK)或false(表示不OK)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440301.html
標籤:python-3.x 功能 if 语句
