How to run a Python script in terminal, Linux, macOS, and Windows
If you need a quick answer on how to run a Python script from the command line, one line does it: type python3 script.py on Linux and macOS, or py script.py on Windows (or python script.py if the interpreter is in your PATH).
Real automation jobs rarely stop at a single local file, though. Scraping pipelines and backend tasks need isolated packages, command-line arguments, background execution after you close SSH, and clean proxy routing. Below, we walk through every practical method across Linux, macOS, and Windows, updated for Python 3.15, the uv tool (PEP 723), and common environment errors.
Checking your installed Python version first
Before running any code, check which Python binary your terminal calls. As of late 2026, Python 3.15 (patch 3.15.2) is the current stable branch, versions 3.11 through 3.14 remain supported, and Python 3.10 reached end-of-life on October 1, 2026.
Open your terminal: press Ctrl + Alt + T (or connect over SSH) on Linux, open Terminal via Spotlight (Cmd + Space) or Applications > Utilities on macOS, or launch Windows Terminal (PowerShell) or Command Prompt (Win + R > cmd) on Windows.
Verify the installed version and executable path using the commands for your OS.
On Linux and macOS:
python3 --version
which python3Expected output:
Python 3.15.2
/usr/bin/python3
On Windows (PowerShell or Command Prompt):
py --version
where.exe pythonExpected output:
Python 3.15.2
C:\Users\cyberyozh\AppData\Local\Programs\Python\Python315\python.exe
Using Python Install Manager on Windows: the official pymanager installer (PEP 773, shipped as the default Windows installer for Python 3.15) sets up the py command automatically with no manual PATH edits. Run py list at any time to view every installed runtime.
The sections below cover each execution method in order - from a basic file in the terminal to background services and proxy-routed scripts.
How to run a Python script in the terminal: step-by-step
This workflow fits both local development on your machine and running scripts on a server.
Step 1. Create a script with a clear entry point
Save your code in a plain text file ending in .py, such as hello.py. Wrap the main call inside if __name__ == "__main__": so the code runs only when you execute the file directly, not when another module imports functions from it.
from pathlib import Path
import platform
def main() -> None:
script_dir = Path(__file__).resolve().parent
print(f"Python {platform.python_version()} running from {script_dir}")
if __name__ == "__main__":
main()Resolve relative paths with Path(__file__).resolve().parent instead of os.getcwd(). On Windows, launching a script via double-click under Python Install Manager or via Task Scheduler often sets the working folder to C:\Windows\System32. Anchoring paths to __file__ keeps file lookups consistent across Linux, macOS, and Windows.
If your script is large, check its syntax before running it with the built-in compiler python3 -m py_compile hello.py. For directory-wide checks and CI workflows, read our Python syntax checker guide.
Step 2. Open the project folder and run the script
Move into the folder containing hello.py with cd and pass the filename to the interpreter.
On Linux and macOS:
cd /path/to/your/project
python3 hello.pyOn Windows:
cd C:\path\to\your\project
py hello.pyExpected output:
Python 3.15.2 running from /path/to/your/project
Running without cd: you can pass the full path to the file from any directory. If any folder name includes spaces, wrap the path in quotes: python3 "/home/cyberyozh/my scripts/hello.py".
Useful Python command-line flags
You can place flags before the filename to control imports, debugging, and log output:
Command | What it does | When to use it |
python3 script.py | Executes a .py file top to bottom | Standard runs for local and server scripts |
python3 -m package.module | Finds and runs a module on sys.path by name | Running built-in or package modules (python3 -m http.server, python3 -m pytest) without breaking relative imports |
python3 -u script.py | Disables buffering on stdout and stderr | Writing logs right away with no delay under nohup, Docker, and systemd |
python3 -i script.py | Drops into the interactive >>> prompt after the file finishes | Inspecting variable values in memory right after a run |
python3 -c "print(2 ** 10)" | Runs a short snippet without creating a .py file | One-line checks in shell scripts and CI steps |
python3 -X utf8=0 script.py | Turns off default UTF-8 mode in Python 3.15+ | Temporary compatibility with legacy files in local Windows code pages |
Step 3. Isolate dependencies in a .venv virtual environment
Current Ubuntu, Debian, Fedora, and macOS (Homebrew) releases block global pip installs with an externally-managed-environment error (PEP 668) so user packages do not break OS tools. Create a local virtual environment inside your project folder instead:
Create .venv by running python3 -m venv .venv on Linux and macOS, or py -m venv .venv on Windows.
Activate the environment using the command for your shell below.
Install packages with python -m pip install requests python-dotenv and run your script with python hello.py.
Exit the virtual environment when finished by typing deactivate.
Shell / OS | Activation command | Direct run without activation |
Linux and macOS (Bash, Zsh) | source .venv/bin/activate | .venv/bin/python hello.py |
Windows Command Prompt (cmd) | .venv\Scripts\activate.bat | .venv\Scripts\python.exe hello.py |
Windows PowerShell | .\.venv\Scripts\Activate.ps1 | .venv\Scripts\python.exe hello.py |
If PowerShell blocks Activate.ps1: when you see "running scripts is disabled on this system," allow local scripts once for your user account (no admin rights needed) using the command below. For deeper PEP 668 and pip troubleshooting, see our guide to fixing the externally-managed-environment error in pip.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserStep 4. Run a single file with third-party packages via uv (PEP 723)
When you want to share a single .py file with a teammate or copy it to a fresh server, maintaining a separate .venv and requirements.txt adds extra steps. Python's PEP 723 standard solves this by storing the minimum Python version and package list inside a TOML comment block at the top of the file. The uv tool reads that header, builds an isolated cached environment automatically, and executes the code.
Initialize inline metadata and add a package with uv init --script check_ip.py --python 3.12 and uv add --script check_ip.py "httpx[socks]>=0.28".
Add your script logic below the # /// script block, as shown in the example below.
Run the file with uv run check_ip.py without setting up .venv manually.
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "httpx[socks]>=0.28",
# ]
# ///
import os
import httpx
proxy_url = os.environ.get("CYBERYOZH_PROXY")
with httpx.Client(proxy=proxy_url, timeout=15.0) as client:
response = client.get("https://api.ipify.org?format=json")
response.raise_for_status()
print("Active exit IP:", response.json()["ip"])The -S flag on line 1 (#!/usr/bin/env -S uv run --script) tells Linux to split the arguments properly - without it, the kernel treats the entire uv run --script string as one program name and fails. To pin exact dependency versions before moving the file to a server, generate a lock file with uv lock --script check_ip.py.
How to run a Python script in Linux and macOS without typing python3
If you run the same console utility often, calling it directly as ./script.py saves typing:
Put #!/usr/bin/env python3 on line 1 of the file with no blank lines above it.
Grant execute permission with chmod +x script.py.
Run the file from its folder with ./script.py.
#!/usr/bin/env python3
print("Executable script started.")Calling /usr/bin/env python3 picks the first Python 3 binary in your active PATH (including an activated .venv), which is more portable than hardcoding /usr/bin/python3.
Tip: to run the script from any directory without the ./ prefix, move it into ~/.local/bin/ and confirm that folder is exported in PATH inside ~/.bashrc or ~/.zshrc.
Passing command-line arguments and environment variables
Hardcoding URLs, retry counts, or passwords inside source files makes code harder to reuse and increases the risk of leaking secrets to Git. Pass runtime flags through the built-in argparse module and keep credentials in a .env file.
Example cli_worker.py:
#!/usr/bin/env python3
import argparse
import sys
def main() -> int:
parser = argparse.ArgumentParser(
description="Fetch a status summary for a target host."
)
parser.add_argument("target", help="Target URL or hostname")
parser.add_argument("--retries", type=int, default=3, help="Retry count")
args = parser.parse_args()
print(f"Target: {args.target} | Retries: {args.retries}")
return 0
if __name__ == "__main__":
sys.exit(main())Example run with a target URL and retry count:
python3 cli_worker.py https://example.com --retries 5Expected output:
Target: https://example.com | Retries: 5
Returning an exit code via sys.exit(main()) (0 on success, non-zero on error) lets shell wrappers, schedulers, and CI pipelines detect failures automatically.
Change in Python 3.15 (PEP 686): text-mode open() now defaults to UTF-8 on every OS, including Windows. If the same code also runs on servers using Python 3.11-3.14, keep passing encoding="utf-8" explicitly.
How to run a Python script in the background and on a schedule
Closing an SSH session on a Linux server sends SIGHUP to child processes and stops any foreground script. Pick a background runner based on how long the task runs and whether it needs auto-restarts:
Tool | OS | When it fits | Example command or setup |
nohup with -u | Linux, macOS | One-off long runs over SSH | nohup /path/.venv/bin/python -u script.py > output.log 2>&1 & |
tmux or screen | Linux, macOS | Interactive runs you want to detach and inspect live later | tmux new -s job -> run script -> detach with Ctrl + B, then D |
systemd | Linux servers | Always-on scripts needing auto-start on reboot and crash restarts | Unit /etc/systemd/system/worker.service + systemctl enable --now worker.service |
cron (crontab) | Linux, macOS | Scheduled runs (every 5 minutes, hourly, or daily) | 0 3 * * * /path/.venv/bin/python /path/script.py >> /path/cron.log 2>&1 |
pythonw and Task Scheduler | Windows | Windowless runs or recurring scheduled jobs on desktop Windows | pythonw script.py or a task pointing to .venv\Scripts\python.exe |
Running in the background with nohup and unbuffered logs
When output goes to a file, Python buffers lines in memory and writes them to disk with a delay. Adding -u disables buffering so fresh log entries appear right away:
nohup /home/cyberyozh/project/.venv/bin/python -u /home/cyberyozh/project/worker.py > /home/cyberyozh/project/output.log 2>&1 &Check the running process with ps aux | grep worker.py and stop it with kill <PID> (or pkill -f worker.py once you confirm no other process shares that name).
Deploying a persistent Linux service with systemd
When a script needs to run continuously and recover from crashes or server reboots, create a service file at /etc/systemd/system/my-worker.service:
[Unit]
Description=Python automation worker
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=cyberyozh
WorkingDirectory=/home/cyberyozh/project
EnvironmentFile=/home/cyberyozh/project/.env
ExecStart=/home/cyberyozh/project/.venv/bin/python -u /home/cyberyozh/project/worker.py
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.targetReload the config, enable the service, and follow its live output:
sudo systemctl daemon-reload
sudo systemctl enable --now my-worker.service
sudo systemctl status my-worker.service
journalctl -u my-worker.service -fImportant for systemd and cron: always point ExecStart and crontab lines to the full path of the environment binary (.venv/bin/python) instead of calling source activate - background schedulers do not load your interactive shell profile.
How to run a Python script in VS Code, PyCharm, and Jupyter
Editors and IDEs call the exact same Python binary underneath while making breakpoints and virtual environments easier to switch:
VS Code: install the official Microsoft Python extension, open the Command Palette (Ctrl + Shift + P on Windows/Linux or Cmd + Shift + P on macOS), select Python: Select Interpreter to bind .venv, and click the Run button in the top-right corner (or press Ctrl + F5).
PyCharm: open your project folder, set .venv under Settings > Project > Python Interpreter, right-click your .py file, and click Run (repeat runs with Shift + F10).
Jupyter Notebook / IPython: execute an external script directly from a notebook cell with the built-in %run script.py command.
How to run a Python script with CyberYozh App proxies
Scripts that query public product catalogs, check regional landing pages, or track prices quickly hit 429 Too Many Requests when every call leaves from one office or server IP. Moving proxy settings into a .env file keeps your code clean and lets you assign a dedicated IP and region to each project.

Loading proxy settings from .env in requests and httpx
Save your connection details from the CyberYozh App dashboard in a local .env file, and add .env to .gitignore right away so keys never enter Git:
PROXY_URL=socks5h://username:password@host:port
CYBERYOZH_API_KEY=your_api_key_hereWhy socks5h:// instead of socks5://: the trailing h tells requests (with PySocks) and httpx 0.28+ to resolve DNS hostnames on the proxy server rather than querying your local ISP's DNS.
Example run_with_proxy.py using requests:
import os
import sys
import requests
from dotenv import load_dotenv
load_dotenv()
proxy_url = os.getenv("PROXY_URL")
if not proxy_url:
print("PROXY_URL is missing in .env", file=sys.stderr)
sys.exit(1)
with requests.Session() as session:
session.proxies = {"http": proxy_url, "https": proxy_url}
try:
response = session.get("https://api.ipify.org?format=json", timeout=15)
response.raise_for_status()
print("Exit IP:", response.json()["ip"])
except requests.RequestException as exc:
print(f"Request failed: {exc}", file=sys.stderr)
sys.exit(2)Install the required packages with python -m pip install "requests[socks]" python-dotenv and execute python run_with_proxy.py.
If your project uses httpx 0.28 or newer, pass the singular string argument httpx.Client(proxy=proxy_url). The older proxies={...} dictionary was removed in httpx 0.28 and raises TypeError.
Managing proxies and IP checks via the CyberYozh App REST API
To manage proxies, SMS activations, and risk checks straight from Python without opening a browser, follow the CyberYozh App REST API documentation (https://app.cyberyozh.com/api/v1/ for proxies, SMS, and checkers; https://app.cyberyozh.com/api/v2/rotating-proxies/ for rotating pools) using the X-Api-Key header:
import os
import sys
import requests
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("CYBERYOZH_API_KEY")
if not api_key:
print("Set CYBERYOZH_API_KEY in .env before running.", file=sys.stderr)
sys.exit(1)
headers = {
"Accept": "application/json",
"X-Api-Key": api_key,
}
response = requests.get(
"https://app.cyberyozh.com/api/v1/proxies/history/",
headers=headers,
timeout=15,
)
response.raise_for_status()
payload = response.json()
records = payload.get("results", payload) if isinstance(payload, dict) else payload
print("Proxy records fetched:", len(records))Before starting large runs, check your exit address in the built-in IP Fraud Score checker - it evaluates IPQualityScore, ThreatMetrix, and 118 public blacklists before your script sends traffic.
Choosing a proxy type for your Python script
Match the proxy type to your request rate, required IP persistence, and target website checks:
Proxy type | Tasks for Python | CyberYozh App specs | Traffic & pricing |
Public catalog scraping, price tracking, SERP monitoring, AI data collection | 100M+ residential IPs across 195+ countries, Advanced IP filtering, free geo-targeting (country, region, city), per-request rotation or sticky sessions up to 24 hours, 99.9% uptime, REST API | Per-GB billing with automatic monthly traffic rollover (Pay-as-you-go packages from $4/GB with a 3 GB minimum, scaling to $2.50/GB at 100 GB) | |
Trust-sensitive platforms, mobile-layout checks, parallel Google SERP scraping | Real carrier modems and SIMs, dedicated and shared channels, manual and API IP rotation (shared channels rotate every 5 or 30 min), HTTP/HTTPS, SOCKS5, UDP, VPN/VLESS, OS TCP/IP fingerprint switching | Unlimited traffic; from $1.70/day | |
Ongoing work over weeks or months, recurring QA tests, client projects | Dedicated static real ISP IP for the full rental term, HTTP/HTTPS and SOCKS5, 99.9% uptime | Unlimited traffic; from $5.29/month | |
Open APIs, staging servers, high-speed uptime checks | Dedicated and shared IPv4/IPv6, HTTP and SOCKS5, up to 99.99% uptime | Unlimited traffic on dedicated plans; from $1.77/month |
What to read next for your stack:
Python networking libraries: setting up a proxy for Python, proxy rotation in requests, and optimizing HTTP retries;
browser automation and OS routing: proxies in Playwright and setting up a proxy on Linux;
ready-to-run collection without custom scrapers: CyberYozh App AI solutions and open-source Yozh Scraper.
Common Python startup errors and how to fix them
When a script fails to launch, the culprit is almost always an interpreter path, file permission, or library version rather than your code:
Error message | Cause | Fix |
python: command not found | Linux and macOS expose python3, or Windows PATH does not include Python | Run python3 script.py on Linux/macOS or py script.py on Windows |
can't open file ... No such file or directory | Your terminal is not in the folder holding the script | Check the current folder with pwd and ls (dir on Windows), move via cd, or pass the full quoted path |
ModuleNotFoundError: No module named '...' | The package is installed in another interpreter or .venv is inactive | Activate .venv or install with the exact interpreter running the file: .venv/bin/python -m pip install <package> |
Permission denied on ./script.py | The file lacks execute permission on Linux/macOS | Run chmod +x script.py and verify #!/usr/bin/env python3 is on line 1 |
Activate.ps1 cannot be loaded (PowerShell) | Default Windows PowerShell policy blocks local .ps1 scripts | Run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser once, or call .venv\Scripts\python.exe script.py directly |
error: externally-managed-environment | The OS package manager protects system Python (PEP 668) | Use python3 -m venv .venv or launch through uv run |
SyntaxError: invalid syntax on python script.py | You entered a shell command inside Python's interactive >>> prompt | Exit with exit() (or exit on Python 3.13+) and run the command in your OS shell |
TypeError: Client.__init__() got an unexpected keyword argument 'proxies' | An older httpx snippet is running on version 0.28+ | Replace proxies={...} with the string parameter proxy="socks5h://..." |
UnicodeDecodeError after upgrading to Python 3.15 | PEP 686 defaults open() to UTF-8, exposing legacy cp1252/cp1251 files | Pass the file encoding explicitly: open(..., encoding="cp1252") or encoding="locale" |
Now that you know how to run a Python script reliably across terminals and servers, explore the right IP types and protocols in the CyberYozh App proxy catalog.
