ZetCode

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”命令。

simple_command.py
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 中可用的任何系统命令。 此示例显示了不同平台上的系统信息命令。

system_commands.py
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 命令与文件系统交互。 此示例演示了文件创建、复制和删除。

file_management.py
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 命令。

environment_vars.py
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 一起使用。 此示例演示了如何组合多个命令。

command_chaining.py
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 不捕获输出,但我们可以重定向到文件。 此示例显示了处理命令输出的技术。

command_output.py
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。

安全注意事项

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程