11. Running Python Scripts from the Command Line
1. Introduction
While the Python REPL is great for quick experiments, real projects require saving code into files.
You can then run these Python scripts from the command line.
2. Creating Your First Python Script
- Open any text editor (Notepad, VS Code, PyCharm, etc.).
- Type the following code:
print("Hello from a Python script!")
- Save the file as
hello.py.
3. Running on Windows
- Open Command Prompt.
- Navigate to the folder where you saved
hello.py. Example:
cd C:\Users\YourName\Documents
- Run the script with:
python hello.py
If you have multiple versions of Python, use:
py hello.py
4. Running on macOS/Linux
- Open Terminal.
- Navigate to the folder where you saved
hello.py. Example:
cd ~/Documents
- Run the script with:
python3 hello.py
5. Using Absolute and Relative Paths
You don’t always need to cd into the directory. You can run a script by giving its path:
python3 ~/Documents/hello.py
Or from the current folder:
python3 ./hello.py
6. Adding a Shebang (Linux/macOS only)
At the top of your script, add:
#!/usr/bin/env python3
Make the file executable:
chmod +x hello.py
Now you can run it directly:
./hello.py
7. Passing Arguments to a Script
You can pass values to your script:
python3 hello.py world
In your script:
import sys
print("Hello,", sys.argv[1])
Output:
Hello, world
8. Troubleshooting
- ‘python’ not recognized (Windows) → Use
pyor check that Python was added to PATH during installation. - Permission denied (Linux/macOS) → Use
chmod +x filename.pyto make it executable. - Wrong version running → Specify
python3instead ofpython.
9. Why Run Scripts from the Command Line?
- Reproducible: you can save and run the same script multiple times.
- Shareable: scripts can be distributed to others.
- Practical: most real-world Python projects are run as scripts or applications.
10. Next Steps
✅ You now know how to run Python scripts from the command line.
In the next chapter, we will explore how to use Python with different text editors.