高效辦公 Python 進(jìn)階:操作系統(tǒng)交互的 15 個(gè)高級(jí)命令
在辦公環(huán)境中,Python的強(qiáng)大不僅限于數(shù)據(jù)處理和分析,它還能與操作系統(tǒng)進(jìn)行深度交互,實(shí)現(xiàn)自動(dòng)化任務(wù),極大地提高工作效率。本文將帶你探索Python中用于操作系統(tǒng)交互的15個(gè)高級(jí)命令,通過(guò)實(shí)踐示例讓你掌握這些技巧。
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模塊更高級(jí)的命令執(zhí)行
subprocess模塊提供了更靈活和強(qiáng)大的命令執(zhí)行功能。
import subprocess
# 執(zhí)行命令并獲取輸出
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(f'命令輸出: {result.stdout}')
3. shutil模塊用于文件操作
shutil模塊提供了一系列用于文件操作的高級(jí)功能,如復(fù)制、移動(dòng)和刪除文件。
import shutil
# 復(fù)制文件
shutil.copy('source.txt', 'destination.txt')
4. 遍歷目錄樹(shù)
使用os.walk可以遍歷目錄樹(shù)。
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)建臨時(shí)文件
tempfile模塊用于創(chuàng)建臨時(shí)文件和目錄。
import tempfile
# 創(chuàng)建臨時(shí)文件
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)建路徑對(duì)象
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庫(kù)監(jiān)控系統(tǒng)資源
psutil是一個(gè)跨平臺(tái)庫(kù),用于檢索系統(tǒng)運(yùn)行的進(jìn)程和系統(tǒng)利用率信息。
import psutil
# 獲取CPU使用率
print(f'CPU Usage: {psutil.cpu_percent()}%')
10. watchdog庫(kù)監(jiān)控文件系統(tǒng)變化
watchdog庫(kù)可以監(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庫(kù)進(jìn)行SSH連接
paramiko庫(kù)用于通過(guò)SSH連接到遠(yuǎn)程服務(wù)器。
import paramiko
# 創(chuàng)建SSH客戶(hù)端
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庫(kù)簡(jiǎn)化SSH任務(wù)
fabric是一個(gè)Python庫(kù),用于簡(jiǎn)化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庫(kù)處理cron表達(dá)式
croniter庫(kù)用于解析和迭代cron表達(dá)式。
from croniter import croniter
from datetime import datetime
cron = croniter('*/5 * * * *', datetime.now())
for _ in range(5):
print(cron.get_next(datetime))
14. schedule庫(kù)安排任務(wù)
schedule庫(kù)用于安排周期性任務(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庫(kù)高級(jí)任務(wù)調(diào)度
APScheduler是一個(gè)功能強(qiáng)大的任務(wù)調(diào)度庫(kù)。
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()
實(shí)戰(zhàn)案例:自動(dòng)備份腳本
假設(shè)你需要每天定時(shí)備份某個(gè)目錄到另一個(gè)位置,可以使用shutil和schedule庫(kù)來(lái)實(shí)現(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點(diǎn)執(zhí)行備份任務(wù)
schedule.every().day.at('01:00').do(backup, '/path/to/source', '/path/to/destination')
while True:
schedule.run_pending()
time.sleep(1)
在這個(gè)腳本中,shutil.copytree用于復(fù)制整個(gè)目錄樹(shù),schedule.every().day.at('01:00')用于安排每天凌晨1點(diǎn)執(zhí)行任務(wù)。這樣,你就可以自動(dòng)備份重要數(shù)據(jù),無(wú)需手動(dòng)操作。
總結(jié)
通過(guò)本文,我們學(xué)習(xí)了Python中與操作系統(tǒng)交互的15個(gè)高級(jí)命令,包括執(zhí)行系統(tǒng)命令、文件操作、監(jiān)控文件系統(tǒng)變化、SSH連接、任務(wù)調(diào)度等。這些命令和庫(kù)可以幫助你實(shí)現(xiàn)自動(dòng)化辦公任務(wù),提高工作效率。