在 Python 中,你可以使用 subprocess
模块来调用 Shell 命令。subprocess
模块提供了一个强大而灵活的接口,允许你执行外部命令并与其交互。以下是一些基本的例子:
1. 执行简单的 Shell 命令:
import subprocess
# 使用 subprocess.run 执行简单的 Shell 命令
subprocess.run("ls -l", shell=True)
这将在 Python 中执行 ls -l
命令,输出当前目录的文件列表。
2. 获取命令输出:
你可以使用 subprocess.run
的 stdout
参数来获取命令的输出。
import subprocess
# 获取命令输出
result = subprocess.run("echo Hello, World!", shell=True, stdout=subprocess.PIPE)
# 打印命令输出
print(result.stdout.decode('utf-8'))
这将输出 “Hello, World!”。
3. 传递参数:
import subprocess
# 传递参数执行命令
filename = "example.txt"
result = subprocess.run(["cat", filename], stdout=subprocess.PIPE)
# 打印命令输出
print(result.stdout.decode('utf-8'))
这将执行 cat example.txt
命令,显示文件内容。
4. 检查命令的返回状态:
你可以使用 returncode
属性来检查命令的返回状态。
import subprocess
# 检查命令的返回状态
result = subprocess.run("ls non_existent_directory", shell=True)
# 打印返回状态
if result.returncode == 0:
print("Command executed successfully.")
else:
print(f"Error: {result.returncode}")
这将检查 ls non_existent_directory
命令的返回状态。
请注意,使用 shell=True
可以执行简单的字符串命令,但要小心避免 shell 注入攻击。如果你使用参数化命令,最好将命令和参数作为列表传递,如例子 3 所示。