高效辦公 Python 進階:操作系統(tǒng)交互的 15 個高級命令
在辦公環(huán)境中,Python的強大不僅限于數(shù)據(jù)處理和分析,它還能與操作系統(tǒng)進行深度交互,實現(xiàn)自動化任務(wù),極大地提高工作效率。本文將帶你探索Python中用于操作系統(tǒng)交互的15個高級命令,通過實踐示例讓你掌握這些技巧。
1. 使用os模塊執(zhí)行系統(tǒng)命令
os模塊提供了許多與操作系統(tǒng)交互的功能,比如執(zhí)行系統(tǒng)命令。
import os
# 執(zhí)行系統(tǒng)命令
result = os.system('ls -l')
print(f'命令執(zhí)行結(jié)果: {result}')
2. subprocess模塊更高級的命令執(zhí)行
subprocess模塊提供了更靈活和強大的命令執(zhí)行功能。
import subprocess
# 執(zhí)行命令并獲取輸出
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(f'命令輸出: {result.stdout}')
3. shutil模塊用于文件操作
shutil模塊提供了一系列用于文件操作的高級功能,如復(fù)制、移動和刪除文件。
import shutil
# 復(fù)制文件
shutil.copy('source.txt', 'destination.txt')
4. 遍歷目錄樹
使用os.walk可以遍歷目錄樹。
import os
for root, dirs, files in os.walk('/path/to/directory'):
print(f'Root: {root}, Directories: {dirs}, Files: {files}')
5. glob模塊用于文件匹配
glob模塊可以方便地匹配文件路徑模式。
import glob
# 匹配所有.txt文件
for filename in glob.glob('*.txt'):
print(filename)
6. tempfile模塊創(chuàng)建臨時文件
tempfile模塊用于創(chuàng)建臨時文件和目錄。
import tempfile
# 創(chuàng)建臨時文件
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b'Hello, world!')
print(f'Temp file created: {temp_file.name}')
7. pathlib模塊更現(xiàn)代的路徑操作
pathlib模塊提供了面向?qū)ο蟮奈募到y(tǒng)路徑操作。
from pathlib import Path
# 創(chuàng)建路徑對象
path = Path('/path/to/directory')
# 獲取目錄內(nèi)容
for file in path.iterdir():
print(file)
8. platform模塊獲取系統(tǒng)信息
platform模塊可以獲取操作系統(tǒng)信息。
import platform
print(f'System: {platform.system()}')
print(f'Node Name: {platform.node()}')
print(f'Release: {platform.release()}')
9. psutil庫監(jiān)控系統(tǒng)資源
psutil是一個跨平臺庫,用于檢索系統(tǒng)運行的進程和系統(tǒng)利用率信息。
import psutil
# 獲取CPU使用率
print(f'CPU Usage: {psutil.cpu_percent()}%')
10. watchdog庫監(jiān)控文件系統(tǒng)變化
watchdog庫可以監(jiān)控文件系統(tǒng)的變化,如文件創(chuàng)建、修改和刪除。
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f'File {event.src_path} has been modified')
# 創(chuàng)建事件處理器和觀察者
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
11. paramiko庫進行SSH連接
paramiko庫用于通過SSH連接到遠程服務(wù)器。
import paramiko
# 創(chuàng)建SSH客戶端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username='username', password='password')
# 執(zhí)行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read().decode())
# 關(guān)閉連接
ssh.close()
12. fabric庫簡化SSH任務(wù)
fabric是一個Python庫,用于簡化SSH任務(wù)的執(zhí)行。
from fabric import Connection
c = Connection('hostname', user='username', connect_kwargs={'password': 'password'})
result = c.run('ls -l')
print(result.stdout)
13. croniter庫處理cron表達式
croniter庫用于解析和迭代cron表達式。
from croniter import croniter
from datetime import datetime
cron = croniter('*/5 * * * *', datetime.now())
for _ in range(5):
print(cron.get_next(datetime))
14. schedule庫安排任務(wù)
schedule庫用于安排周期性任務(wù)。
import schedule
import time
def job():
print('Job executed')
# 安排任務(wù)每分鐘執(zhí)行一次
schedule.every(1).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
15. APScheduler庫高級任務(wù)調(diào)度
APScheduler是一個功能強大的任務(wù)調(diào)度庫。
from apscheduler.schedulers.background import BackgroundScheduler
import time
def my_job():
print('Job executed')
scheduler = BackgroundScheduler()
scheduler.add_job(my_job, 'interval', seconds=5)
scheduler.start()
try:
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
實戰(zhàn)案例:自動備份腳本
假設(shè)你需要每天定時備份某個目錄到另一個位置,可以使用shutil和schedule庫來實現(xiàn)。
import shutil
import schedule
import time
from datetime import datetime
def backup(source, destination):
shutil.copytree(source, destination + '/' + datetime.now().strftime('%Y%m%d_%H%M%S'))
print(f'Backup completed at {datetime.now()}')
# 安排每天凌晨1點執(zhí)行備份任務(wù)
schedule.every().day.at('01:00').do(backup, '/path/to/source', '/path/to/destination')
while True:
schedule.run_pending()
time.sleep(1)
在這個腳本中,shutil.copytree用于復(fù)制整個目錄樹,schedule.every().day.at('01:00')用于安排每天凌晨1點執(zhí)行任務(wù)。這樣,你就可以自動備份重要數(shù)據(jù),無需手動操作。
總結(jié)
通過本文,我們學(xué)習了Python中與操作系統(tǒng)交互的15個高級命令,包括執(zhí)行系統(tǒng)命令、文件操作、監(jiān)控文件系統(tǒng)變化、SSH連接、任務(wù)調(diào)度等。這些命令和庫可以幫助你實現(xiàn)自動化辦公任務(wù),提高工作效率。