Python隱藏功能大揭秘 十個(gè)系統(tǒng)調(diào)用功能你必須知道
今天我們要探索Python中的一些隱藏功能,這些功能可以幫助你更高效地與操作系統(tǒng)進(jìn)行交互。從簡(jiǎn)單的文件操作到高級(jí)的系統(tǒng)監(jiān)控,這些功能將讓你大開(kāi)眼界。話不多說(shuō),讓我們開(kāi)始吧!
1.os.system() - 執(zhí)行外部命令
os.system() 是 Python 中執(zhí)行外部命令的最簡(jiǎn)單方法之一。它會(huì)等待命令執(zhí)行完成并返回命令的退出狀態(tài)碼。
import os
# 執(zhí)行系統(tǒng)命令
result = os.system('echo Hello, World!')
print(f'Command executed with exit status: {result}')
輸出結(jié)果:
Hello, World!
Command executed with exit status: 0
解釋:os.system() 直接調(diào)用系統(tǒng)命令行執(zhí)行指定的命令,并打印命令的輸出。
2.subprocess.run() - 更強(qiáng)大的外部命令執(zhí)行
subprocess.run() 提供了比os.system() 更強(qiáng)大和靈活的外部命令執(zhí)行功能,可以捕獲命令的輸出。
import subprocess
# 執(zhí)行系統(tǒng)命令并捕獲輸出
result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print(f'Command output: {result.stdout}')
print(f'Command exit status: {result.returncode}')
輸出結(jié)果:
Command output: Hello, World!
Command exit status: 0
解釋:subprocess.run() 返回一個(gè)CompletedProcess 實(shí)例,包含命令的標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯(cuò)誤和退出狀態(tài)碼。
3.os.environ - 訪問(wèn)環(huán)境變量
os.environ 是一個(gè)字典,用于訪問(wèn)和修改環(huán)境變量。
import os
# 訪問(wèn)環(huán)境變量
python_path = os.environ.get('PYTHONPATH')
print(f'PYTHONPATH: {python_path}')
# 設(shè)置環(huán)境變量
os.environ['MY_VAR'] = 'Hello, Python!'
print(f'MY_VAR: {os.environ.get("MY_VAR")}')
輸出結(jié)果:
PYTHONPATH: (your PYTHONPATH)
MY_VAR: Hello, Python!
解釋:通過(guò)os.environ 可以方便地訪問(wèn)和修改當(dāng)前進(jìn)程的環(huán)境變量。
4.os.walk() - 遍歷目錄樹(shù)
os.walk() 生成目錄樹(shù)下的所有文件名,通過(guò)遍歷目錄樹(shù),可以方便地處理文件和目錄。
import os
# 遍歷目錄樹(shù)
for root, dirs, files in os.walk('/path/to/directory'):
print(f'Root: {root}')
print(f'Directories: {dirs}')
print(f'Files: {files}')
print('-' * 40)
輸出結(jié)果:
Root: /path/to/directory
Directories: ['subdir1', 'subdir2']
Files: ['file1.txt', 'file2.txt']
----------------------------------------
Root: /path/to/directory/subdir1
Directories: []
Files: ['file3.txt']
----------------------------------------
Root: /path/to/directory/subdir2
Directories: []
Files: ['file4.txt']
----------------------------------------
解釋:os.walk() 返回一個(gè)三元組(root, dirs, files),分別表示當(dāng)前目錄路徑、子目錄列表和文件列表。
5.shutil.copy() - 文件復(fù)制
shutil.copy() 用于復(fù)制文件,支持不同文件系統(tǒng)和設(shè)備之間的復(fù)制。
import shutil
# 復(fù)制文件
source_file = '/path/to/source/file.txt'
destination_file = '/path/to/destination/file.txt'
shutil.copy(source_file, destination_file)
print(f'File copied from {source_file} to {destination_file}')
輸出結(jié)果:
File copied from /path/to/source/file.txt to /path/to/destination/file.txt
解釋:shutil.copy() 將源文件復(fù)制到目標(biāo)位置,如果目標(biāo)文件已存在,會(huì)被覆蓋。
6.shutil.rmtree() - 遞歸刪除目錄
shutil.rmtree() 用于遞歸刪除目錄及其內(nèi)容,類似于 Unix/Linux 的rm -rf 命令。
import shutil
# 遞歸刪除目錄
directory_to_remove = '/path/to/directory'
shutil.rmtree(directory_to_remove)
print(f'Directory {directory_to_remove} removed')
輸出結(jié)果:
Directory /path/to/directory removed
解釋:shutil.rmtree() 遞歸地刪除指定目錄及其所有子目錄和文件。
7.psutil - 獲取系統(tǒng)信息
psutil 是一個(gè)跨平臺(tái)庫(kù),用于輕松獲取系統(tǒng)運(yùn)行的進(jìn)程和系統(tǒng)利用率(CPU、內(nèi)存、磁盤(pán)、網(wǎng)絡(luò)等)信息。
import psutil
# 獲取CPU使用率
cpu_usage = psutil.cpu_percent(interval=1)
print(f'CPU Usage: {cpu_usage}%')
# 獲取內(nèi)存使用率
memory_info = psutil.virtual_memory()
print(f'Total Memory: {memory_info.total / (1024 ** 3):.2f} GB')
print(f'Available Memory: {memory_info.available / (1024 ** 3):.2f} GB')
輸出結(jié)果:
CPU Usage: 10.5%
Total Memory: 16.00 GB
Available Memory: 8.00 GB
解釋:psutil 提供了一組函數(shù)來(lái)獲取系統(tǒng)硬件和軟件資源的使用情況。
8.platform - 獲取平臺(tái)信息
platform 模塊用于獲取當(dāng)前系統(tǒng)的平臺(tái)信息,如操作系統(tǒng)類型、版本等。
import platform
# 獲取操作系統(tǒng)信息
system = platform.system()
version = platform.version()
architecture = platform.architecture()
print(f'System: {system}')
print(f'Version: {version}')
print(f'Architecture: {architecture}')
輸出結(jié)果:
System: Darwin
Version: 21.1.0
Architecture: ('64bit', '')
解釋:platform 模塊提供了一系列函數(shù)來(lái)獲取當(dāng)前系統(tǒng)的詳細(xì)信息。
9.tempfile - 創(chuàng)建臨時(shí)文件和目錄
tempfile 模塊用于創(chuàng)建臨時(shí)文件和目錄,這些文件和目錄在程序結(jié)束時(shí)會(huì)自動(dòng)刪除。
import tempfile
# 創(chuàng)建臨時(shí)文件
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
temp_file.write('Hello, Temp File!')
temp_file_path = temp_file.name
print(f'Temporary file created at: {temp_file_path}')
# 創(chuàng)建臨時(shí)目錄
temp_dir = tempfile.TemporaryDirectory()
print(f'Temporary directory created at: {temp_dir.name}')
temp_dir.cleanup() # 手動(dòng)清理臨時(shí)目錄
輸出結(jié)果:
Temporary file created at: /var/folders/xx/yy/T/tmpk123456
Temporary directory created at: /var/folders/xx/yy/T/tmpabcdefg
解釋:tempfile.NamedTemporaryFile() 創(chuàng)建臨時(shí)文件,tempfile.TemporaryDirectory() 創(chuàng)建臨時(shí)目錄,這些文件和目錄在不再需要時(shí)會(huì)自動(dòng)刪除。
10.signal - 處理信號(hào)
signal 模塊用于處理操作系統(tǒng)信號(hào),如中斷(Ctrl+C)等。
import signal
import time
# 定義信號(hào)處理函數(shù)
def signal_handler(sig, frame):
print(f'Signal {sig} received. Exiting...')
exit(0)
# 注冊(cè)信號(hào)處理函數(shù)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C to exit...')
while True:
time.sleep(1)
輸出結(jié)果:
Press Ctrl+C to exit...
(Press Ctrl+C)
Signal 2 received. Exiting...
解釋:signal.signal() 注冊(cè)一個(gè)信號(hào)處理函數(shù),當(dāng)接收到指定信號(hào)時(shí),調(diào)用該函數(shù)。在這個(gè)例子中,當(dāng)接收到中斷信號(hào)(Ctrl+C)時(shí),程序會(huì)優(yōu)雅地退出。
實(shí)戰(zhàn)案例:系統(tǒng)監(jiān)控腳本
現(xiàn)在,我們將上述知識(shí)結(jié)合起來(lái),編寫(xiě)一個(gè)簡(jiǎn)單的系統(tǒng)監(jiān)控腳本,每隔一定時(shí)間記錄一次CPU和內(nèi)存的使用情況。
import psutil
import time
import os
def log_system_info(log_file):
with open(log_file, 'a') as f:
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
f.write(f'Timestamp: {time.strftime("%Y-%m-%d %H:%M:%S")}\n')
f.write(f'CPU Usage: {cpu_usage}%\n')
f.write(f'Total Memory: {memory_info.total / (1024 ** 3):.2f} GB\n')
f.write(f'Available Memory: {memory_info.available / (1024 ** 3):.2f} GB\n')
f.write('-' * 40 + '\n')
if __name__ == "__main__":
log_file = 'system_monitor.log'
interval = 10 # 監(jiān)控間隔(秒)
print(f'Logging system information to {log_file} every {interval} seconds...')
try:
while True:
log_system_info(log_file)
time.sleep(interval)
except KeyboardInterrupt:
print('Monitoring stopped.')
分析:這個(gè)腳本每隔一定時(shí)間記錄一次系統(tǒng)的CPU和內(nèi)存使用情況,并將信息寫(xiě)入日志文件中。當(dāng)按下 Ctrl+C 時(shí),腳本會(huì)優(yōu)雅地停止運(yùn)行。
總結(jié)
通過(guò)今天的文章,我們探索了Python中一些強(qiáng)大的隱藏功能,這些功能涵蓋了從執(zhí)行外部命令到系統(tǒng)監(jiān)控的各個(gè)方面。我們學(xué)習(xí)了如何使用os 和subprocess 模塊執(zhí)行系統(tǒng)命令,shutil 模塊進(jìn)行文件和目錄操作,psutil 模塊獲取系統(tǒng)信息,以及signal 模塊處理操作系統(tǒng)信號(hào)。最后,我們通過(guò)一個(gè)實(shí)戰(zhàn)案例展示了如何將這些知識(shí)結(jié)合起來(lái),編寫(xiě)一個(gè)系統(tǒng)監(jiān)控腳本。