Python os.system 函数
上次修改时间:2025 年 4 月 11 日
本综合指南探讨了 Python 的 os.system 函数,该函数执行 shell 命令。我们将介绍命令执行、返回值、安全注意事项和实际示例。
基本定义
os.system 函数在子 shell 中执行命令。 它接受一个字符串命令并返回进程的退出状态。
主要特征:阻塞直到完成,使用系统 shell(Unix 上为 /bin/sh,Windows 上为 cmd.exe),成功时返回 0,失败时返回非零。
执行简单命令
os.system 最基本用法是运行单个 shell 命令。 此示例演示了在类 Unix 系统上执行“ls”命令。
import os
# Execute a simple command
return_code = os.system("ls -l")
# Print the return code
print(f"Command returned: {return_code}")
# Check if command succeeded
if return_code == 0:
print("Command executed successfully")
else:
print("Command failed")
这将在 shell 中运行“ls -l”并捕获返回码。 返回码 0 通常表示成功,而非零表示失败。
请注意,命令输出直接发送到 stdout,而不是由 Python 捕获。 对于输出捕获,请考虑使用 subprocess.run。
运行系统命令
os.system 可以执行 shell 中可用的任何系统命令。 此示例显示了不同平台上的系统信息命令。
import os
import platform
# Platform-specific commands
system = platform.system()
if system == "Linux":
os.system("uname -a")
os.system("df -h")
elif system == "Windows":
os.system("systeminfo")
os.system("wmic diskdrive get size")
elif system == "Darwin":
os.system("sw_vers")
os.system("diskutil list")
else:
print("Unsupported system")
此脚本检测操作系统并运行相应的系统命令。 输出直接出现在运行 Python 的控制台中。
平台检测有助于编写跨平台脚本,使其能够自动适应不同的操作系统。
创建和管理文件
os.system 可以使用 shell 命令与文件系统交互。 此示例演示了文件创建、复制和删除。
import os
# Create a file
os.system("echo 'Hello World' > test.txt")
# Copy the file
os.system("cp test.txt test_copy.txt")
# List files
os.system("ls -l *.txt")
# Delete files
os.system("rm test.txt test_copy.txt")
# Verify deletion
os.system("ls -l *.txt || echo 'No text files found'")
此脚本使用 shell 命令执行基本的文件操作。 每个命令按顺序运行,只有在前一个命令完成后才启动下一个命令。
虽然 Python 具有内置的文件操作功能,但在复杂的操作或与现有 shell 脚本集成时,shell 命令可能很有用。
命令中的环境变量
Shell 命令可以使用环境变量,这些环境变量可以从 Python 设置。 此示例演示如何将 Python 变量传递给 shell 命令。
import os
# Set variables in Python
username = "testuser"
log_dir = "/var/log"
# Use variables in shell commands
os.system(f"echo 'Processing logs for {username}'")
os.system(f"ls -l {log_dir} | head -n 5")
# Set environment variables
os.environ["TEMP_DIR"] = "/tmp"
os.system('echo "Temporary directory is $TEMP_DIR"')
# Complex command with variables
file_count = 5
os.system(f"for i in $(seq 1 {file_count}); do touch file_$i.txt; done")
os.system("ls file_*.txt")
可以使用 f-strings 将 Python 变量插入到 shell 命令中。 在 Python 中设置的环境变量可用于子 shell。
谨慎使用变量插值,以避免 shell 注入漏洞。 清理任何用户提供的输入。
命令链接和管道
命令链接和管道等 shell 功能可与 os.system 一起使用。 此示例演示了如何组合多个命令。
import os
# Simple command chain
os.system("date && echo 'Command successful' || echo 'Command failed'")
# Pipeline example
os.system("ps aux | grep python | head -n 5")
# Complex pipeline with redirection
os.system("grep -r 'import os' . 2>/dev/null | wc -l > count.txt")
# Read the result back
with open("count.txt") as f:
print(f"Found {f.read().strip()} occurrences")
# Clean up
os.system("rm count.txt")
这显示了如何使用 && (AND)、|| (OR) 和 |(管道)等 shell 功能。 输出重定向的工作方式与正常的 shell 用法相同。
命令链接可以使复杂的操作简洁,但对于不熟悉 shell 语法的人来说,可能会降低可读性。
处理命令输出
虽然 os.system 不捕获输出,但我们可以重定向到文件。 此示例显示了处理命令输出的技术。
import os
# Redirect output to a file
os.system("ls -l / > dir_listing.txt")
# Read the output file
with open("dir_listing.txt") as f:
print("Directory listing:")
print(f.read())
# Temporary file pattern
import tempfile
with tempfile.NamedTemporaryFile() as tmp:
os.system(f"uname -a > {tmp.name}")
print("\nSystem info:")
print(tmp.read().decode())
# Error handling
os.system("ls nonexistent_dir 2> errors.txt")
with open("errors.txt") as f:
print("\nErrors:")
print(f.read())
可以通过重定向到文件,然后读取这些文件来捕获输出。 临时文件提供了比手动管理文件更简洁的方法。
对于更高级的输出处理,请考虑使用 subprocess.Popen 或 subprocess.run。
安全注意事项
- Shell 注入:避免在命令中使用未经清理的用户输入
- 平台差异:命令在不同操作系统上的行为可能不同
- 错误处理:检查返回码以确定命令是否成功
- 替代方案:优先使用 subprocess 以获得更多控制
- 环境:命令在具有当前环境的子 shell 中运行
最佳实践
- 输入清理:始终清理动态命令部分
- 返回码检查:验证命令是否成功
- 平台意识:在目标平台上测试命令
- 错误处理:处理潜在的命令失败
- 文档:清楚地记录 shell 依赖项
资料来源
作者
列出所有 Python 教程。