zaro

How to run a Python file in terminal?

Published in Python Execution 2 mins read

To run a Python file in the terminal, you need to navigate to the directory containing your Python script and then execute it using the python command followed by the script's name.

Steps to Run a Python File

Here is a detailed guide on how to run a Python file using the terminal:

  1. Open the Terminal: First, open your terminal application. This is usually done through your operating system's application menu or by using a keyboard shortcut.

  2. Navigate to the Script's Directory: Use the cd (change directory) command to navigate to the directory where your Python script is saved. For example, if your script my_script.py is in the folder Documents/MyProjects, you would type the following in the terminal:

    cd Documents/MyProjects
  3. Execute the Python Script: Once you are in the correct directory, use the python command followed by the name of your script to execute it. For my_script.py, you would enter:

    python my_script.py
  • Linux Consideration: On Linux systems, it's a good practice to use python3 instead of python to ensure you're using Python 3. This is because some systems might have both Python 2 and Python 3 installed, and python might default to an older version. So, on Linux, you might use:

    python3 my_script.py
  • This ensures you are using a modern Python version.

Command Breakdown

Here's a quick summary of the commands:

Command Description Example
cd Change directory - used to navigate between directories. cd Documents/MyProjects
python Executes a Python script - can be python or python3 on Linux. python my_script.py or python3 my_script.py

Example

Here is a step-by-step illustration:

Suppose you have a Python file named hello.py in your Documents/MyPython directory, and the file contains:

print("Hello, World!")

You would run this file by:

  1. Open your terminal.
  2. Type cd Documents/MyPython and press Enter.
  3. Type python hello.py (or python3 hello.py on Linux) and press Enter.

The output in your terminal will be:

Hello, World!

Important Considerations

  • File Extension: Ensure your Python script has the .py extension.
  • Python Installation: Python must be installed on your system.
  • File Path: Verify the file path to ensure you are in the correct directory.
  • Permissions: Ensure you have the necessary permissions to execute the file.

By following these steps, you can successfully run your Python scripts from the terminal.