IPython - System Commands
IPython - System Shell Commands
Section titled “IPython - System Shell Commands”IPython provides seamless integration with the underlying operating system’s shell (like bash, zsh, or the Windows command prompt). This allows you to run system commands directly from your IPython session without leaving the environment.
Running Shell Commands with !
Section titled “Running Shell Commands with !”To execute a system command, simply prefix it with an exclamation mark (!). IPython will run the command in a subshell and display its standard output (and standard error) directly in your session.
# On Linux/macOS:!pwd# Output: (e.g.) /home/user/current_project
!ls -l *.py# Output: (Lists Python files in the current directory)
# On Windows:!cd# Output: (e.g.) C:\Users\User\current_project
!dir *.txt# Output: (Lists text files in the current directory)Capturing Command Output
Section titled “Capturing Command Output”You can capture the output of a shell command into a Python variable. Assign the command (prefixed with !) to a variable name.
# On Linux/macOSfiles = !lsprint(files)# Output: (e.g.) ['data.csv', 'notebook.ipynb', 'script.py']
# On Windowsfiles = !dir /bprint(files)# Output: (e.g.) ['data.csv', 'notebook.ipynb', 'script.py']The output is typically captured as a list of strings (IPython’s SList type, which behaves like a list but has extra methods), with each line of the command’s output becoming an element in the list. Newline characters are usually stripped.
Passing Python Variables to Shell Commands
Section titled “Passing Python Variables to Shell Commands”You can embed Python variables directly into your shell commands using curly braces {} or by prefixing the variable name with a dollar sign $.
filename = 'my_data.txt'message = 'Processing complete.'
# Using curly braces!echo "Processing {filename}" > status.log
# Using dollar sign (works for simple variable names)!echo $message >> status.log
# Verify the file content (Linux/macOS)!cat status.log# Output:# Processing my_data.txt# Processing complete.This powerful feature allows you to dynamically construct shell commands based on the state of your Python program, enabling complex interactions with the system.