如何在Jupyter Notebook内部通过单元格命令启动终端?
Hey there! Glad you asked—since you already know how to spin up a terminal via the Jupyter server's UI, let's cover how to do similar tasks right from a notebook cell, whether you need to run one-off commands or get an interactive session.
1. Run Single/Batch Terminal Commands (Non-Interactive)
This is the most straightforward use case, and it works in almost every Jupyter environment:
Single command: Prefix any terminal command with
!to execute it directly in the cell. The output will print right below the cell. For example:!pwd # Check your current working directory !ls -lh # List directory contents with human-readable sizes !pip list | grep pandas # Filter pip packages to find pandasMulti-line bash script: Use the
%%bashcell magic command at the top of a cell to run multiple bash commands in sequence. The entire cell will be treated as a bash script:%%bash echo "=== Current Environment Details ===" whoami echo "Working directory: $(pwd)" echo "---" # Create a test file and write content to it touch test_file.txt echo "Hello from Jupyter cell!" >> test_file.txt cat test_file.txt
2. Launch an Interactive Terminal Session
Jupyter's web-based cells have some limitations with fully interactive terminal sessions, but there are a couple of workarounds depending on your setup:
Local Jupyter (with a desktop environment): If you're running Jupyter on your local machine, you can launch a native system terminal window directly from a cell. This terminal will use the same working directory and environment as your Jupyter server:
# Linux !xterm & # macOS !open -a Terminal . # Windows !start cmdThe
&at the end of the Linux command lets the terminal run in the background so your Jupyter cell doesn't hang.Interactive shell in the cell: If you need to work directly within the notebook cell (instead of a separate window), you can launch an interactive bash shell with:
!bash -iKeep in mind: Some interactive features (like password prompts or real-time input) might not work perfectly in the web interface due to how Jupyter handles stdin. For these cases, the server UI's terminal is still the better option.
Enhanced interactive shell: If you have
ptpythoninstalled (a feature-rich Python shell), you can run it in the cell for a more polished interactive experience:!ptpython
A quick note for remote servers: If you're running Jupyter on a remote server without a graphical interface, launching a native terminal window won't work. Stick to non-interactive commands or use the server's built-in terminal via the UI for full interactivity.
内容的提问来源于stack exchange,提问作者George Pamfilis

