一、os模塊
Python的os模塊是操作系統相關的函數庫,可以實現操作系統的許多功能。常用的功能包括文件處理、進程管理、系統參數和環境變數等。
文件操作是os模塊最常用的功能之一。可以使用os模塊中的函數來創建、刪除、複製、移動文件或目錄等。例如,使用os模塊中的rename()函數可以重命名一個文件:
import os os.rename('old.txt', 'new.txt')
進程管理是另一個常用的功能。可以使用os模塊中的函數來獲取系統資源和運行進程的信息。例如,使用os模塊中的getpid()函數可以獲取當前運行Python程序的進程ID:
import os pid = os.getpid() print('Current process ID:', pid)
系統參數和環境變數是操作系統中一些重要的配置信息。可以使用os模塊中的函數來獲取這些配置信息。例如,使用os模塊中的environ()函數可以獲取當前環境變數:
import os env = os.environ print('Environment variables:', env)
二、sys模塊
Python的sys模塊是與Python解釋器相關的函數庫,可以控制Python解釋器的行為。常用的功能包括命令行參數、標準輸入輸出和異常處理等。
命令行參數是指在運行Python程序時傳遞給程序的參數。可以使用sys模塊中的argv變數來獲取這些參數。例如,在命令行執行「python test.py arg1 arg2 arg3」時,可以使用以下代碼來獲取這些參數:
import sys args = sys.argv print('Command line arguments:', args)
標準輸入輸出是Python程序與命令行交互的主要方式。可以使用sys模塊中的stdin和stdout變數來控制標準輸入輸出。例如,在命令行中輸入文本時,可以使用以下代碼來獲取這些輸入:
import sys input_data = sys.stdin.readline() print('User input:', input_data)
異常處理是程序設計中非常重要的一部分,可以使用sys模塊中的相關函數來處理異常。例如,使用sys模塊中的exc_info()函數可以獲取當前異常的類型、值和跟蹤信息:
import sys try: result = 1 / 0 except: exc_type, exc_value, exc_traceback = sys.exc_info() print('Exception type:', exc_type) print('Exception value:', exc_value) print('Traceback:', exc_traceback)
三、subprocess模塊
Python的subprocess模塊是一個強大的子進程管理模塊,可以方便地啟動和控制子進程。常用的功能包括執行外部命令、在不同的Shell環境中執行命令和管道操作等。
執行外部命令是subprocess模塊最常用的功能之一。可以使用subprocess模塊中的run()函數來執行外部命令,並獲取命令的輸出和返回值。例如,執行「ls -l」命令並獲取輸出結果:
import subprocess result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) output = result.stdout.decode('utf-8') print('Command output:', output)
管道操作是另一個常用的功能。可以使用subprocess模塊中的Popen()函數來啟動多個進程,並通過管道連接它們。例如,啟動一個進程來生成隨機數,並通過管道將輸出傳遞給另一個進程:
import subprocess p1 = subprocess.Popen(['python', 'randint.py'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['python', 'sum.py'], stdin=p1.stdout, stdout=subprocess.PIPE) output = p2.communicate()[0].decode('utf-8') print('Command output:', output)
在不同的Shell環境中執行命令是另一個常用的功能。可以使用subprocess模塊中的shell參數來指定要執行命令的Shell環境。例如,執行「echo $HOME」命令並獲取輸出結果:
import subprocess result = subprocess.run('echo $HOME', shell=True, stdout=subprocess.PIPE) output = result.stdout.decode('utf-8') print('Command output:', output)
四、threading模塊
Python的threading模塊是一個多線程管理模塊,可以方便地實現並發編程。常用的功能包括創建線程、線程同步和線程間通信等。
創建線程是threading模塊最基本的功能。可以使用threading模塊中的Thread類來創建線程,並指定要執行的函數。例如,創建一個簡單的線程:
import threading def thread_func(): print('Thread started') print('Thread finished') t = threading.Thread(target=thread_func) t.start()
線程同步是多線程編程中非常重要的一部分,可以使用threading模塊中的Lock類來實現線程同步。例如,創建一個共享變數,並在多個線程之間對它進行加鎖和解鎖:
import threading total = 0 lock = threading.Lock() def thread_func(): global total with lock: for i in range(1000000): total += 1 threads = [] for i in range(10): t = threading.Thread(target=thread_func) threads.append(t) for t in threads: t.start() for t in threads: t.join() print('Total:', total)
線程間通信是多線程編程中另一個重要的一部分,可以使用threading模塊中的Queue類來實現線程間通信。例如,創建一個隊列,並在兩個線程之間傳遞數據:
import queue import threading q = queue.Queue() def producer_func(): for i in range(10): q.put(i) def consumer_func(): while True: item = q.get() if item is None: break print(item) threads = [] t1 = threading.Thread(target=producer_func) t2 = threading.Thread(target=consumer_func) threads.append(t1) threads.append(t2) for t in threads: t.start() for t in threads: t.join() q.put(None)
五、concurrent.futures模塊
Python的concurrent.futures模塊是一個高級的並發編程模塊,可以方便地實現非同步編程和並行計算。常用的功能包括線程池、進程池和非同步執行等。
線程池是concurrent.futures模塊中最基本的功能之一。可以使用concurrent.futures模塊中的ThreadPoolExecutor類來創建線程池,並在池中執行任務。例如,使用線程池計算斐波那契數列:
import concurrent.futures def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: future_list = [executor.submit(fib, i) for i in range(10)] for future in concurrent.futures.as_completed(future_list): print(future.result())
進程池是concurrent.futures模塊中另一個常用的功能。可以使用concurrent.futures模塊中的ProcessPoolExecutor類來創建進程池,並在池中執行任務。例如,使用進程池計算素數:
import concurrent.futures def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor: future_list = [executor.submit(is_prime, i) for i in range(100)] for future in concurrent.futures.as_completed(future_list): if future.result(): print(future.args[0], 'is prime')
非同步執行是concurrent.futures模塊中另一個高級的功能。可以使用concurrent.futures模塊中的asyncio庫來實現非阻塞式的非同步執行。例如,使用asyncio庫實現HTTP客戶端:
import asyncio async def fetch_url(url): async with aiohttp.request('GET', url) as response: assert response.status == 200 return await response.read() async def main(): urls = ['http://example.com', 'http://google.com', 'http://python.org'] tasks = [fetch_url(url) for url in urls] completed, pending = await asyncio.wait(tasks) for task in completed: print(task.result()) loop = asyncio.get_event_loop() loop.run_until_complete(main())
六、總結
本文介紹了Python中與操作系統和系統相關的四個模塊:os、sys、subprocess和threading。這些模塊提供了強大的功能,可以方便地實現文件操作、進程管理、系統參數和環境變數、命令行傳參、標準輸入輸出、異常處理、子進程管理、多線程編程、非同步編程和並行計算等。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154546.html