Python 實戰項目:結合 while 循環和 time 模塊的 15 個創意應用
Python 的 while 循環和 time 模塊是非常實用的工具,可以用來創建各種有趣的應用。今天我們就來探索一下如何將這兩個工具結合起來,實現一些創意十足的小項目。從簡單的倒計時器到復雜的自動化任務,我們會一步步引導你完成這些項目。
1. 倒計時器
首先,我們來做一個簡單的倒計時器。這個項目會從用戶輸入的時間開始倒數,直到時間結束。
import time
# 獲取用戶輸入的時間(秒)
seconds = int(input("請輸入倒計時的秒數: "))
while seconds > 0:
print(f"倒計時: {seconds} 秒")
time.sleep(1) # 暫停1秒
seconds -= 1
print("時間到!")
解釋:
- input() 函數獲取用戶輸入的時間。
- while 循環在 seconds 大于 0 時繼續執行。
- time.sleep(1) 讓程序暫停1秒。
- 每次循環后,seconds 減少1,直到為0。
2. 進度條
接下來,我們做一個進度條,顯示任務的完成進度。
import time
total_steps = 100
step = 0
while step <= total_steps:
percent = (step / total_steps) * 100
bar = ('=' * int(percent / 2)).ljust(50)
print(f"[{bar}] {percent:.2f}%", end='\r')
time.sleep(0.1) # 模擬任務處理時間
step += 1
print("\n任務完成!")
解釋:
- total_steps 定義總步數。
- while 循環在 step 小于等于 total_steps 時繼續執行。
- percent 計算當前進度的百分比。
- bar 創建進度條字符串。
- end='\r' 讓輸出在同一行更新。
- time.sleep(0.1) 模擬任務處理時間。
3. 簡易鬧鐘
我們可以用 while 循環和 time 模塊制作一個簡易鬧鐘。
import time
# 獲取用戶輸入的鬧鐘時間(格式:HH:MM)
alarm_time = input("請輸入鬧鐘時間 (HH:MM): ")
current_time = time.strftime("%H:%M")
while current_time != alarm_time:
current_time = time.strftime("%H:%M")
time.sleep(1)
print("鬧鐘響了!")
解釋:
- input() 獲取用戶輸入的鬧鐘時間。
- time.strftime("%H:%M") 獲取當前時間。
- while 循環在當前時間不等于鬧鐘時間時繼續執行。
- time.sleep(1) 每秒檢查一次時間。
4. 自動刷新網頁
如果你需要定期刷新某個網頁,可以用 selenium 庫結合 while 循環和 time 模塊來實現。
from selenium import webdriver
import time
# 啟動瀏覽器
driver = webdriver.Chrome()
url = "https://www.example.com"
refresh_interval = 60 # 刷新間隔(秒)
while True:
driver.get(url)
print("頁面已刷新")
time.sleep(refresh_interval)
解釋:
- webdriver.Chrome() 啟動 Chrome 瀏覽器。
- driver.get(url) 打開指定的網頁。
- while True 無限循環。
- time.sleep(refresh_interval) 每隔一段時間刷新一次頁面。
5. 數據采集
使用 requests 庫和 while 循環,可以定期從某個網站抓取數據。
import requests
import time
url = "https://api.example.com/data"
interval = 30 # 抓取間隔(秒)
while True:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print("請求失敗")
time.sleep(interval)
解釋:
- requests.get(url) 發送 HTTP GET 請求。
- response.status_code 檢查響應狀態碼。
- response.json() 解析 JSON 格式的數據。
- time.sleep(interval) 每隔一段時間抓取一次數據。
6. 自動發送郵件
使用 smtplib 和 email 庫,結合 while 循環和 time 模塊,可以定期發送郵件。
import smtplib
from email.mime.text import MIMEText
import time
sender = 'your_email@example.com'
receiver = 'receiver_email@example.com'
password = 'your_password'
subject = '定期郵件'
body = '這是一封定期發送的郵件。'
msg = MIMEText(body)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(sender, password)
send_interval = 3600 # 發送間隔(秒)
while True:
server.sendmail(sender, receiver, msg.as_string())
print("郵件已發送")
time.sleep(send_interval)
解釋:
- MIMEText 創建郵件內容。
- smtplib.SMTP 連接 SMTP 服務器。
- server.starttls() 啟用 TLS 加密。
- server.login() 登錄郵箱。
- server.sendmail() 發送郵件。
- time.sleep(send_interval) 每隔一段時間發送一次郵件。
7. 自動備份文件
可以定期備份文件,確保數據安全。
import shutil
import time
import os
source_file = 'path/to/source/file.txt'
backup_dir = 'path/to/backup/directory'
backup_interval = 3600 # 備份間隔(秒)
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
while True:
backup_file = os.path.join(backup_dir, f"backup_{int(time.time())}.txt")
shutil.copy(source_file, backup_file)
print(f"文件已備份到 {backup_file}")
time.sleep(backup_interval)
解釋:
- shutil.copy() 復制文件。
- os.path.join() 拼接備份文件路徑。
- os.makedirs() 創建備份目錄。
- time.time() 獲取當前時間戳。
- time.sleep(backup_interval) 每隔一段時間備份一次文件。
8. 實時監控系統資源
使用 psutil 庫,可以實時監控系統的 CPU 和內存使用情況。
import psutil
import time
check_interval = 5 # 監控間隔(秒)
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_usage = psutil.virtual_memory().percent
print(f"CPU 使用率: {cpu_usage}%")
print(f"內存使用率: {memory_usage}%")
time.sleep(check_interval)
解釋:
- psutil.cpu_percent(interval=1) 獲取 CPU 使用率。
- psutil.virtual_memory().percent 獲取內存使用率。
- time.sleep(check_interval) 每隔一段時間檢查一次系統資源。
9. 自動下載文件
可以定期從某個 URL 下載文件。
import requests
import time
import os
url = "https://example.com/file.zip"
download_dir = 'path/to/download/directory'
download_interval = 3600 # 下載間隔(秒)
if not os.path.exists(download_dir):
os.makedirs(download_dir)
while True:
file_name = os.path.join(download_dir, f"file_{int(time.time())}.zip")
response = requests.get(url)
if response.status_code == 200:
with open(file_name, 'wb') as file:
file.write(response.content)
print(f"文件已下載到 {file_name}")
else:
print("下載失敗")
time.sleep(download_interval)
解釋:
- requests.get(url) 發送 HTTP GET 請求。
- response.content 獲取文件內容。
- with open(file_name, 'wb') as file 寫入文件。
- time.sleep(download_interval) 每隔一段時間下載一次文件。
10. 自動重啟服務
如果某個服務掛了,可以自動重啟它。
import subprocess
import time
service_name = 'your_service'
check_interval = 60 # 檢查間隔(秒)
while True:
result = subprocess.run(['systemctl', 'is-active', service_name], capture_output=True, text=True)
if 'inactive' in result.stdout:
subprocess.run(['systemctl', 'start', service_name])
print(f"{service_name} 已重啟")
else:
print(f"{service_name} 正在運行")
time.sleep(check_interval)
解釋:
- subprocess.run() 執行系統命令。
- capture_output=True 捕獲命令輸出。
- text=True 以文本形式返回輸出。
- time.sleep(check_interval) 每隔一段時間檢查一次服務狀態。
11. 自動更新軟件
可以定期檢查并更新軟件。
import subprocess
import time
update_command = 'sudo apt update && sudo apt upgrade -y'
check_interval = 3600 # 檢查間隔(秒)
while True:
subprocess.run(update_command, shell=True)
print("軟件已更新")
time.sleep(check_interval)
解釋:
- subprocess.run(update_command, shell=True) 執行更新命令。
- time.sleep(check_interval) 每隔一段時間更新一次軟件。
12. 自動清理日志文件
定期清理日志文件,防止磁盤空間被占滿。
import os
import time
log_dir = 'path/to/log/directory'
cleanup_interval = 3600 # 清理間隔(秒)
while True:
for file_name in os.listdir(log_dir):
file_path = os.path.join(log_dir, file_name)
if os.path.isfile(file_path):
os.remove(file_path)
print(f"已刪除 {file_path}")
time.sleep(cleanup_interval)
解釋:
- os.listdir(log_dir) 獲取日志目錄中的文件列表。
- os.path.join(log_dir, file_name) 拼接文件路徑。
- os.remove(file_path) 刪除文件。
- time.sleep(cleanup_interval) 每隔一段時間清理一次日志文件。
13. 自動同步文件夾
可以定期同步兩個文件夾的內容。
import shutil
import time
import os
source_dir = 'path/to/source/directory'
target_dir = 'path/to/target/directory'
sync_interval = 3600 # 同步間隔(秒)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
while True:
for item in os.listdir(source_dir):
source_item = os.path.join(source_dir, item)
target_item = os.path.join(target_dir, item)
if os.path.isfile(source_item):
shutil.copy(source_item, target_item)
print(f"已同步 {source_item} 到 {target_item}")
elif os.path.isdir(source_item):
shutil.copytree(source_item, target_item)
print(f"已同步 {source_item} 到 {target_item}")
time.sleep(sync_interval)
解釋:
- shutil.copy() 復制文件。
- shutil.copytree() 復制目錄。
- time.sleep(sync_interval) 每隔一段時間同步一次文件夾。
14. 自動發送短信
使用 twilio 庫,可以定期發送短信。
from twilio.rest import Client
import time
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
to_phone_number = '+1234567890'
from_phone_number = '+0987654321'
message_body = '這是一條定期發送的短信。'
send_interval = 3600 # 發送間隔(秒)
while True:
message = client.messages.create(
to=to_phone_number,
from_=from_phone_number,
body=message_body
)
print(f"短信已發送,消息ID: {message.sid}")
time.sleep(send_interval)
解釋:
- Client(account_sid, auth_token) 創建 Twilio 客戶端。
- client.messages.create() 發送短信。
- time.sleep(send_interval) 每隔一段時間發送一次短信。
15. 自動記錄系統事件
可以定期記錄系統事件,方便后續分析。
import logging
import time
log_file = 'path/to/log/file.log'
log_interval = 60 # 記錄間隔(秒)
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s')
while True:
logging.info("系統正常運行")
time.sleep(log_interval)
解釋:
- logging.basicConfig() 配置日志記錄。
- logging.info() 記錄日志信息。
- time.sleep(log_interval) 每隔一段時間記錄一次系統事件。
實戰案例:自動備份數據庫
假設你有一個 MySQL 數據庫,需要定期備份。我們可以結合 while 循環和 time 模塊來實現這個功能。
import os
import time
import subprocess
db_host = 'localhost'
db_user = 'root'
db_password = 'your_password'
db_name = 'your_database'
backup_dir = 'path/to/backup/directory'
backup_interval = 3600 # 備份間隔(秒)
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
while True:
timestamp = int(time.time())
backup_file = os.path.join(backup_dir, f"{db_name}_{timestamp}.sql")
# 構建 mysqldump 命令
dump_cmd = f"mysqldump -h {db_host} -u {db_user} -p{db_password} {db_name} > {backup_file}"
# 執行備份命令
subprocess.run(dump_cmd, shell=True)
print(f"數據庫已備份到 {backup_file}")
time.sleep(backup_interval)
解釋:
- os.makedirs(backup_dir) 創建備份目錄。
- timestamp 獲取當前時間戳。
- dump_cmd 構建 mysqldump 命令。
- subprocess.run(dump_cmd, shell=True) 執行備份命令。
- time.sleep(backup_interval) 每隔一段時間備份一次數據庫。
總結
本文介紹了如何結合 while 循環和 time 模塊實現15個創意應用,包括倒計時器、進度條、簡易鬧鐘、自動刷新網頁、數據采集、自動發送郵件、自動備份文件、實時監控系統資源、自動下載文件、自動重啟服務、自動更新軟件、自動清理日志文件、自動同步文件夾、自動發送短信、自動記錄系統事件,以及一個實戰案例:自動備份數據庫。