shell_commands
Shell 命令
Section titled “Shell 命令”IPython 提供了一种便捷的方式,可以直接从交互式会话或 Notebook 中与底层操作系统的 shell 进行交互。这使得您无需离开 Python 环境即可运行系统命令,例如列出文件、创建目录或使用命令行工具。
使用 ! 运行 Shell 命令
Section titled “使用 ! 运行 Shell 命令”任何以感叹号(!)开头的行都会被视为 shell 命令,并由系统的默认 shell 执行(例如 Linux/macOS 上的 bash 或 Windows 上的 cmd.exe)。
# 列出当前目录下的文件 (Linux/macOS)!ls -l
# 列出当前目录下的文件 (Windows)!dir
# 打印当前工作目录 (使用 Python 实现跨平台)!python -c "import os; print(os.getcwd())"
# 创建新目录!mkdir my_new_directory
# 显示网络配置 (Linux/macOS)!ifconfig# (或在较新版 Linux 上使用 !ip addr)
# 显示网络配置 (Windows)!ipconfigshell 命令的输出会直接打印在 cell 下方。
捕获 Shell 命令输出
Section titled “捕获 Shell 命令输出”您可以将 shell 命令的输出赋值给一个 Python 变量。IPython 会捕获标准输出 (stdout),并将其作为字符串列表返回(按换行符分割)。
files = !lsprint(f"Type of 'files': {type(files)}")print(f"Number of files/dirs: {len(files)}")print("First few entries:")for i, f in enumerate(files[:5]): print(f" {i}: {f}")
# Windows 示例:dir_output = !dir *.txtprint(dir_output)注意:这会捕获标准输出 (stdout)。打印到标准错误输出 (stderr) 的错误通常仍然会直接显示,但不会被捕获到变量中,除非您使用 shell 重定向(例如,!command 2>&1)。输出格式有时可能包含用于颜色的终端转义码,如果在程序中处理,可能需要清理。
在 Shell 命令中使用 Python 变量
Section titled “在 Shell 命令中使用 Python 变量”您可以直接将 Python 变量嵌入到 shell 命令中。主要有两种方式:
1. 使用花括号 {}
Section titled “1. 使用花括号 {}”将 Python 变量名放在 shell 命令字符串的花括号 {} 内。
filename = "my_data.txt"message = "Hello from Python!"
# Create a file with content from a Python variable!echo {message} > {filename}
# Display the file content!cat {filename}# (use !type {filename} on Windows)
# List the specific file!ls -l {filename}2. 使用美元符号 $
Section titled “2. 使用美元符号 $”另一种方式是在 Python 变量名前加上美元符号 $。这种语法类似于 shell 变量扩展,但在 IPython 中作用于 Python 变量。
dirname = "new_folder"
# Create the directory using the variable!mkdir $dirname
# Check if it exists!ls -d $dirname
# Pass a list of arguments (IPython handles expansion)files_to_list = ["my_data.txt", dirname]!ls -l {files_to_list} # Works with braces too# !ls -l $files_to_list # $ syntax might be less robust for lists/complex objects通常更推荐使用 {} 语法,因为它更明确,并且处理不同类型(如列表)时通常更具可预测性。
集成 shell 命令对于以下任务很有用:
- 文件和目录管理(如
ls,dir,mkdir,rm,cp,mv)。 - 运行命令行工具(例如
grep,awk,curl,wget)。 - 版本控制操作(如
!git status,!git log)。 - 编译代码或运行外部进程。
- 快速系统检查(如
!pwd,!uname -a,!hostname)。
虽然 Python 的 os 和 subprocess 模块为复杂的交互提供了更多控制,但 ! 语法为交互式工作流程中的简单 shell 操作提供了一种快速简便的方式。