Back to blog

How to Run Python Code in Terminal

The terminal might seem intimidating at first, but it's one of the most powerful tools for Python development. The terminal gives you direct control over your Python environment for such tasks as running scripts, managing packages, or debugging code. In this guide, we'll walk you through everything you need to know about using Python in the terminal, from basic commands to advanced troubleshooting techniques.

Dominykas Niaura

Aug 20, 2025

10 min read

TL;DR

Install packages with pip install package_name. Check your Python version with python --version. Run scripts with python filename.py. Stop scripts with CTRL+C. Use python to start the interactive shell.

Quick start guide for absolute beginners

If you're completely new to using the terminal, here are the essential steps to get any Python script running in minutes, whether you find it in our blog posts or write it yourself.

Creating and running your first script

  1. Put a code sample into any text editor (Notepad on Windows, TextEdit on macOS, or gedit on Linux).
  2. Save the file with a .py extension, such as code.py.
  3. Open your terminal (search for "Terminal" in Spotlight on macOS, Applications menu on Linux, or "Command Prompt" in the Start menu on Windows).
  4. Choose one of these options:

    a) Type python (with a space after) and drag your .py file directly into the terminal window, then press Enter.

    b) Navigate to the folder containing your file using cd and type python filename.py, and press Enter.Your script will execute immediately!
  5. Your script will execute immediately!

How to navigate to a folder using cd

  • Windows. Right-click your .py file → Properties → copy the folder path from "Location"
  • macOS. Right-click your .py file → Get Info → copy the path under "Where"
  • Linux. Right-click your .py file → Properties → copy the folder path

Then in the terminal:

  • Type cd (with a space)
  • Paste the folder path you copied without the file name
  • Press Enter
  • Now type python filename.py

Or simpler: if your file is on Desktop, just type cd Desktop (or cd ~/Desktop on macOS/Linux).

Handy everyday commands

These simple commands will help you handle 90% of your daily terminal interactions:

  • After running a script, press the up arrow key to recall your last command, then hit Enter to run it again without retyping. This saves enormous time during development.
  • To clear your terminal window when it gets cluttered, type clear and press Enter (or cls on Windows).
  • If a program is running and you want to stop it, press Ctrl+C.
  • To see what files are in your current directory, use ls on macOS/Linux or dir on Windows.
  • When you need to navigate to a different folder, use cd foldername to enter a folder, or cd .. to go back up one level.

What is the terminal and why use it for Python?

The terminal (also called command line or command prompt) is a text-based interface that allows you to interact with your computer using commands. For Python developers, the terminal offers several advantages over graphical interfaces:

  • Direct execution control. Run Python scripts with precise parameters and arguments without clicking through multiple menus.
  • Package management. Install, update, and manage Python libraries efficiently using pip commands.
  • Debugging capabilities. Access detailed error messages and stack traces that help identify and fix issues quickly.
  • Automation potential. Create batch operations and automate repetitive tasks using command-line tools.
  • Professional workflow. Most development environments and production servers rely heavily on terminal operations.

The terminal becomes especially valuable when working with virtual environments, deploying applications, or collaborating on projects where consistent command-line operations ensure reproducible results across different systems.

Installing and setting up Python for terminal use

Before diving into terminal commands, you need Python properly installed and configured on your system.

Installing Python

  • Windows. Download Python from their website and run the installer. Crucially, check the "Add Python to PATH" box during installation. This ensures you can run Python commands from any terminal location.
  • macOS. Python comes pre-installed, but it's often an older version. Install the latest version using Homebrew (brew install python) or download from their website.
  • Linux. Most distributions include Python by default. Update with your package manager if needed (sudo apt update && sudo apt install python3 on Ubuntu/Debian).

Verifying your installation

Open your terminal and run these commands to confirm Python is working:

python --version
python3 --version

You should see output like "Python 3.11.2" or similar. If you get an error message like "command not found," Python isn't properly added to your system PATH.

Configuring your PATH

If Python commands aren't recognized, you need to add Python to your system PATH:

  • Windows. Search for "Environment Variables" in the Start menu, edit your user PATH, and add the Python installation directory (typically C:\Users\YourName\AppData\Local\Programs\Python\Python311\).
  • macOS/Linux. Navigate to your Home folder and press Cmd+Shift+. on macOS or Ctrl+H on Linux to reveal hidden files. Open either the .bashrc or .zshrc file with any text editor and add this line:
export PATH="/usr/local/bin/python3:$PATH"

Essential Python terminal commands

Once Python is properly installed, the commands in this section form the foundation of terminal-based Python development.

Getting help

Essential for discovering new functionality, this command displays all available command-line options and their descriptions:

python -h
python --help

Running single commands

Perfect for quick calculations or testing small code snippets, the -c flag lets you execute Python code directly from the command line without creating a separate file:

python -c "print('Hello, World!')"
python -c "import math; print(math.pi)"

Running modules

The -m flag runs Python modules as scripts. This approach ensures you're using the correct Python environment and is the recommended way to run many built-in tools:

python -m http.server 8000
python -m pip install requests
python -m venv myproject

Package management with pip

pip is Python's package installer. Use it to manage external libraries and dependencies for your projects:

pip install package_name
pip list
pip show package_name
pip uninstall package_name

Running Python scripts from the terminal

The most common terminal operation is executing Python scripts. The following commands show you how to do it effectively.

Basic script execution

Always ensure you're in the correct directory or provide the full file path. This runs your Python file using the system's default Python interpreter:

python filename.py
python3 filename.py

Passing arguments to scripts

Your script can accept arguments using the sys.argv list or the argparse module. This makes your scripts flexible and reusable with different inputs:

python script.py arg1 arg2 arg3
python data_processor.py input.csv output.csv --verbose

Running scripts from different directories

You can execute scripts from anywhere on your system by providing the full path. Use forward slashes on all systems (Windows accepts them too):

python /path/to/script.py
python ../scripts/analyzer.py
cd /project/directory && python main.py

Handling file paths and navigation

Understanding basic navigation commands helps you organize projects and run scripts from the correct locations:

pwd # Show current directory
ls # List files (macOS/Linux)
dir # List files (Windows)
cd /path/to/directory # Change directory
cd .. # Go up one directory

Using the Python interactive shell (REPL)

The Python REPL (Read-Eval-Print Loop) is a powerful tool for testing code, exploring libraries, and learning Python interactively.

Starting the interactive shell

The following command opens an interactive Python session where you can type commands and see results immediately. The prompt changes to ">>>" indicating you're in Python mode:

python
python3

Basic REPL features

  • Multi-line code. The REPL automatically detects when you're writing multi-line statements like functions or loops, changing the prompt to "..." for continuation lines.
  • History access. Use the up and down arrow keys to recall previous commands. This saves time when testing variations of the same code.
  • Tab completion. Press Tab to auto-complete variable names, function names, and module attributes. Extremely helpful for exploring unfamiliar libraries.
  • Help system. Type help() to enter the interactive help system, or help(function_name) to get documentation for specific functions.

When to use REPL vs. scripts

Use REPL for:

  • Testing small code snippets
  • Exploring new libraries
  • Debugging specific functions
  • Learning Python syntax
  • Quick calculations

Use scripts for:

  • Longer programs
  • Code you want to save and reuse
  • Automated processes
  • Production applications

Exiting the Python shell

Use the commands below to exit the Python shell, or use keyboard shortcuts: Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows):

exit()
quit()

Working with Python modules and packages

The terminal provides powerful tools for managing Python modules and packages, essential for any serious Python development. These commands show you how to use Python's built-in tools, install external libraries, and manage your project dependencies.

Running built-in modules

Many built-in modules include useful command-line interfaces. The -m flag ensures you're using the module from your current Python environment:

python -m calendar 2025 8 # Display August 2025 calendar
python -m json.tool data.json # Pretty-print JSON file
python -m timeit "sum(range(100))" # Benchmark code execution
python -m http.server # Start local web server
python -c "import requests; print(requests.get('https://httpbin.org/ip', proxies={'http': 'proxy-server:port'}).text)" # Test proxy connection

Installing packages with pip

pip connects to the Python Package Index (PyPI) to download and install packages. The Requests library, for example, is essential for web scraping projects and HTTP requests, and works seamlessly with proxy configurations for tasks like data collection and avoiding IP blocks:

pip install requests
pip install numpy==1.21.0 # Install specific version
pip install -r requirements.txt # Install from file
pip install --upgrade package_name # Update package

Managing package information

These commands help you understand your Python environment and create reproducible setups for other developers:

pip list # Show all installed packages
pip show requests # Detailed package information
pip freeze > requirements.txt # Export package list
pip check # Verify package dependencies

Troubleshooting module issues

  • Import errors. Use python -c "import module_name" to test if a module loads correctly.
  • Path problems. Check python -c "import sys; print(sys.path)" to see where Python looks for modules.
  • Version conflicts. Use pip list to identify conflicting package versions.

Environment variables and Python path

Understanding how Python finds modules and configures itself is crucial for effective terminal use.

Understanding PYTHONPATH

PYTHONPATH tells Python where to look for modules beyond the standard library and site-packages directory:

echo $PYTHONPATH # View current PYTHONPATH (macOS/Linux)
echo %PYTHONPATH% # View current PYTHONPATH (Windows)
export PYTHONPATH="/path/to/modules:$PYTHONPATH" # Add directory (macOS/Linux)
set PYTHONPATH=C:\path\to\modules;%PYTHONPATH% # Add directory (Windows)

Setting environment variables

Environment variables provide a way to configure Python applications without modifying code:

export DEBUG=True # Set variable (macOS/Linux)
set DEBUG=True # Set variable (Windows)
python -c "import os; print(os.environ.get('DEBUG'))" # Check variable in Python

Virtual environments basics

Virtual environments isolate package installations between projects, preventing conflicts and ensuring reproducible builds:

python -m venv myproject # Create virtual environment
source myproject/bin/activate # Activate (macOS/Linux)
myproject\Scripts\activate # Activate (Windows)
deactivate # Deactivate environment

Common terminal commands for Python development

Beyond Python-specific commands, several general terminal operations significantly improve your development workflow.

File and directory management

mkdir project_name # Create directory
touch filename.py # Create empty file (macOS/Linux)
type nul > filename.py # Create empty file (Windows)
cp source.py destination.py # Copy file (macOS/Linux)
copy source.py destination.py # Copy file (Windows)
rm filename.py # Delete file (macOS/Linux)
del filename.py # Delete file (Windows)

Viewing and editing files

cat script.py # Display file contents (macOS/Linux)
type script.py # Display file contents (Windows)
head -10 data.txt # Show first 10 lines
tail -10 logfile.txt # Show last 10 lines
nano script.py # Edit with nano (macOS/Linux)
notepad script.py # Edit with Notepad (Windows)

Version control basics

git init # Initialize Git repository
git add script.py # Stage file for commit
git commit -m "Add new script" # Commit changes
git status # Check repository status
git log --oneline # View commit history

Troubleshooting common Python terminal issues

Even experienced developers encounter terminal-related Python problems. Here's how to diagnose and fix the most common issues:

"Python not found" errors

If a command like python --version returns "command not found" or "is not recognized," then you might be dealing with a known "Python not found" error. Try these solutions:

  • Verify Python installation by checking installed programs
  • Add Python to your system PATH manually
  • Start the command with python3 instead of python
  • Reinstall Python with the "Add to PATH" option enabled

Always check the PATH option during Python installation and test commands immediately after installation.

Permission errors

If you get "Permission denied" when running scripts or installing packages, try the following:

  • Use chmod +x script.py to make scripts executable (macOS/Linux)
  • Run the terminal as an administrator when necessary (Windows)
  • Install packages in user space with pip install --user package_name
  • Use virtual environments to avoid system-wide permission issues

Version conflicts

If your scripts work in one environment but fail in another, or you experience unexpected behavior from imported modules, try these solutions:

  • Check Python version with python --version
  • Verify package versions with pip list
  • Use virtual environments to isolate project dependencies
  • Create requirements.txt files to document exact package versions

Path and import issues

If you get "ModuleNotFoundError" for modules you know are installed:

  • Check if you're in a virtual environment when you shouldn't be (or vice versa)
  • Verify module installation with pip show module_name
  • Check Python path with python -c "import sys; print('\n'.join(sys.path))"
  • Ensure you're using the correct Python interpreter

Python terminal best practices

Developing effective terminal habits early in your Python journey saves time and prevents frustrations later. Keep in mind these best practices for project organization, command efficiency, development workflow, and security.

Project organization

  • Create dedicated project directories. Keep each Python project in its own folder with clear, descriptive names.
  • Use virtual environments consistently. Create a new virtual environment for each project to avoid dependency conflicts.
  • Maintain requirements files. Document your project dependencies with pip freeze > requirements.txt and update them regularly.

Command efficiency

  • Learn keyboard shortcuts. Use tab completion, command history (up/down arrows), and Ctrl+C to interrupt running programs.
  • Create aliases for common commands. Set up shortcuts for frequently used command combinations.
  • Use descriptive file names. Choose script names that clearly indicate their purpose and functionality.

Development workflow

  • Test scripts incrementally. Run small portions of your code frequently rather than writing large scripts and testing them all at once.
  • Keep terminals organized. Use multiple terminal windows or tabs for different aspects of your project (running scripts, installing packages, version control).
  • Document your commands. Keep notes about useful command combinations and project-specific setup instructions.

Security considerations

  • Verify package sources. Only install packages from trusted sources and double-check package names to avoid typosquatting attacks.
  • Use virtual environments. Isolate your projects to minimize the impact of potentially malicious packages.
  • Be cautious with system-wide installations. Prefer user-level installations (pip install --user) when possible.

Advanced terminal techniques

Once you're comfortable with basic terminal operations, these advanced techniques can significantly boost your productivity. They let you run multiple Python scripts together, manage long-running programs, and create automated data processing workflows.

Command chaining and operators

python script1.py && python script2.py # Run script2 only if script1 succeeds
python process.py || echo "Script failed" # Show message if script fails
python analyzer.py > output.txt # Redirect output to file
python reader.py < input.txt # Use file as input

Background processes and job control

python long_running_script.py & # Run in background
jobs # List active jobs
fg %1 # Bring job 1 to foreground
Ctrl+Z # Suspend current process

Using pipes for data processing

python generate_data.py | python filter.py | python analyze.py
cat data.csv | python process.py > results.txt

To sum up

The terminal is a powerful companion for your Python journey. It’s a convenient tool because it lets you run code, install packages, and manage projects quickly, all from one place.

Start with the basics: python filename.py & pip install package_name, and slowly explore more tools like virtual environments. Practice a little every day, and you'll be surprised how quickly it becomes second nature!

About the author

Dominykas Niaura

Technical Copywriter

Dominykas brings a unique blend of philosophical insight and technical expertise to his writing. Starting his career as a film critic and music industry copywriter, he's now an expert in making complex proxy and web scraping concepts accessible to everyone.


Connect with Dominykas via LinkedIn

All information on Decodo Blog is provided on an as is basis and for informational purposes only. We make no representation and disclaim all liability with respect to your use of any information contained on Decodo Blog or any third-party websites that may belinked therein.

How do I check if Python is installed on my system?

Open your terminal and type python --version or python3 --version. If Python is installed, you'll see version information like "Python 3.11.2". If you get an error message, Python either isn't installed or isn't properly added to your system PATH.

What's the difference between python and python3 commands?

On many systems, python refers to Python 2.x (which is deprecated), while python3 refers to Python 3.x. Some modern systems alias python to python3 by default, while others require you to use python3 to execute scripts. Check both commands to see which version works on your system or set an alias manually.

How do I run a Python script from the terminal?

Navigate to the directory containing your script using cd, then type python filename.py (replace filename.py with your actual file name). You can also provide the full path: python /path/to/your/script.py.

How do I pass arguments to a Python script?

Add arguments after the script name: python script.py arg1 arg2 arg3. Access these in your script using sys.argv or the argparse module.

Why do I get "Python not found" or "command not recognized" errors?

This usually means Python isn't installed or isn't added to your system PATH. Reinstall Python with the "Add Python to PATH" option checked, or manually add Python to your environment variables.

How do I exit the Python interactive shell?

Type exit(), quit(), or use keyboard shortcuts: Ctrl+D on macOS/Linux or Ctrl+Z followed by Enter on Windows.

How do I install Python packages from the terminal?

Use the pip command: pip install package_name. For example, pip install requests installs the Requests library. Use pip list to see installed packages.

What is PYTHONPATH and when should I modify it?

PYTHONPATH is an environment variable that tells Python where to look for modules. You typically only need to modify it when working with custom modules in non-standard locations.

How do I create and use virtual environments?

Create with python -m venv project_name, activate with source project_name/bin/activate (macOS/Linux) or project_name\Scripts\activate (Windows), and deactivate with deactivate.

Can I run Python code without creating a script file?

Yes, use python -c "your_code_here" for single-line commands or start the interactive shell with python for multi-line experimentation.

How do I troubleshoot import errors?

Check if the module is installed with pip show module_name, verify you're in the correct virtual environment, and examine Python's module search path with python -c "import sys; print(sys.path)".

Should I use python or python3 in my commands?

Start with python since it's simpler and works on most modern systems. If you get a "command not found" error, try python3 instead. If python works but shows "Python 2.x" when you check python --version, switch to using python3 commands. Most recent Python installations automatically set up python to point to Python 3, so the shorter command usually works fine.

🐍 Python Web Scraping: In-Depth Guide 2025

Welcome to 2025, the year of the snake – and what better way to celebrate than by mastering Python, the ultimate "snake" in the tech world! If you’re new to web scraping, don’t worry – this guide starts from the basics, guiding you step-by-step on collecting data from websites. Whether you’re curious about automating simple tasks or diving into more significant projects, Python makes it easy and fun to start. Let’s slither into the world of web scraping and see how powerful this tool can be!

Zilvinas Tamulis

Feb 28, 2025

15 min read

Mastering Python Requests - Hero

Mastering Python Requests: A Comprehensive Guide to Using Proxies

When using Python's Requests library, proxies can help with tasks like web scraping, interacting with APIs, or accessing geo-restricted content. Proxies route HTTP requests through different IP addresses, helping you avoid IP bans, maintain anonymity, and bypass restrictions. This guide covers how to set up and use proxies with the Requests library. Let’s get started!

Zilvinas Tamulis

Feb 29, 2024

12 min read

© 2018-2025 decodo.com. All Rights Reserved