A Python script is a file containing Python code, usually with a .py
extension. It can contain anything from a simple one-line command to a complex application. Running these scripts allows you to execute your Python code outside of an interactive environment, making it possible to automate tasks, run complex programs, and share your code with others.
How to run a python script
Creating a Script
To create a Python script, you need a text editor. Let's start by creating a simple one-line command in our text editor (e.g., VS Code):
Saving the Script
Now we are going to save that script. There are a few rules and best practices to consider. These not only ensure that your script works correctly but also help maintain clarity and organization in your codebase.
I will save my script as practice.py
and store it on my desktop. It's crucial to remember the directory where you save your script because we'll need to navigate to that location to run the script later.
Running the Script
To run your Python script from the terminal, follow these steps:
Open the Terminal: Open your terminal or command line interface.
Navigate to the Directory: Use the cd
command to navigate to the directory where your script is saved. For example, if practice.py
is saved on your desktop, you might use a command like:
Execute the Script: Once you are in the correct directory, run the script using the Python interpreter. Depending on your system configuration and Python version, you might use either python
or python3
followed by the script name. For example:
or