Running Python scripts from the terminal is a fundamental skill for any Python developer. In this tutorial, we will cover the basics of running Python scripts from the terminal, including navigating to the correct directory and executing the script.
Installing Python
Before you can run a Python script, you need to have Python installed on your system. You can download the latest version of Python from the official Python website. If you are using a Mac, you can also install Python using Homebrew by running the following command in your terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Once Homebrew is installed, you can install Python by running:
brew install python
Navigating to the Correct Directory
To run a Python script, you need to navigate to the directory where the script is located. You can do this using the cd
command, which stands for "change directory." For example, if your script is located in the Documents/python
directory, you can navigate to that directory by running:
cd ~/Documents/python
The ~
symbol represents your home directory.
Running the Script
Once you are in the correct directory, you can run the Python script using the python
or python3
command, depending on the version of Python you have installed. For example:
python gameover.py
or
python3 gameover.py
You can also specify the absolute path to the script instead of navigating to the directory first:
python ~/Documents/python/gameover.py
or
python3 ~/Documents/python/gameover.py
Tips and Variations
If your filename contains spaces or special characters, you may need to enclose it in quotes when running the script. For example:
python3 "~/Documents/python/some directory with spaces/and a filename with a | character.py"
You can also drag and drop the script into the terminal window to automatically insert the absolute path.
Common Errors
If you encounter an error when trying to run your Python script, make sure that:
- You have Python installed on your system.
- You are in the correct directory.
- The script is named correctly and has a
.py
extension. - There are no typos or syntax errors in the script.
By following these steps and tips, you should be able to successfully run your Python scripts from the terminal.