Essential Python Standard Library Modules for System and File Operations
This article introduces several essential Python standard‑library modules—including os, shutil, subprocess, signal, sys, platform, logging, getpass, pwd, and grp—explaining their primary functions for file and process management, system information, logging, and user/group queries, and provides concise example code for each.
os provides functions for interacting with the operating system, such as reading and writing files, handling directories, and accessing environment variables.
import os
print(os.listdir('.')) # List all files and directories in the specified directoryshutil offers high‑level file operations including copying, moving, deleting, and handling archive files.
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy filesubprocess enables the creation of new processes and connection to their input, output, and error streams, allowing execution of external commands or scripts.
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout) # Print command outputsignal allows programs to receive and handle Unix signals, which is useful for long‑running services.
import signal
def handler(signum, frame):
print("收到信号", signum)
signal.signal(signal.SIGINT, handler) # Set SIGINT signal handlersys gives access to variables and functions closely related to the Python interpreter, such as exiting the program or retrieving command‑line arguments.
import sys
sys.exit() # Exit the current programplatform retrieves underlying platform information, including hardware architecture and operating system name/version.
import platform
print(platform.system()) # Print operating system namelogging provides a flexible logging system that is important for system administration and debugging.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("这是一个日志信息")getpass is used to obtain passwords without echoing them to the screen and also supports retrieving the current username.
import getpass
print(getpass.getuser()) # Get current usernamepwd (Unix) accesses the Unix password database, providing user account information.
import pwd
print(pwd.getpwuid(os.getuid())) # Get current user's account informationgrp (Unix) is similar to pwd but accesses the group database.
import grp
print(grp.getgrgid(os.getgid())) # Get information about the current user's groupTest Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.