What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Run a Python File in Terminal? ( Step-by-Step )

  • Nov 14, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
How to Run a Python File in Terminal? ( Step-by-Step )

Running Python scripts in the terminal is an essential skill for any Python developer. Whether you're a beginner or an experienced programmer, knowing how to execute Python code from the command line is crucial for testing, debugging, and running your programs. In this article, we will explore various techniques and best practices for running Python scripts in the terminal.

What is a Python Script?

A Python script is a file written in the Python programming language and saved with a ".py" extension. It contains a sequence of instructions or code that can be executed by a Python interpreter. Python scripts can range from simple one-liners to complex programs with thousands of lines of code. The file size can be determined by using several methods.

How Python Scripts are Executed?

When you run a Python script, the Python interpreter reads and executes the code line by line. It interprets the instructions and performs the specified actions. The interpreter compiles the code into a lower-level language called bytecode, which is then executed by the Python Virtual Machine (PVM). The PVM is responsible for running the bytecode and producing the desired output. This is how you can read a python file line by line.

Why run a Python file in a terminal?

A terminal or command-line interface is a text-based interface through which one can perform commands using the operating system’s shell.  MacOS and Linux operating systems have Terminals and Windows has Command Prompt.

Running python code through the terminal is the simplest and the most fundamental way one can run programs. Learning how to do that will allow them to understand how the process actually works. Not just that, this knowledge is essential for automation. Automating tasks and scripts requires a good understanding of the terminal.

Terminals can also be used in cases of debugging. Some IDEs do not show the full error output and that could lead to a lot of confusion about where the code is going wrong. Running the same code in a terminal, you can read the entire error and understand the error message to make changes to the code, essentially debugging the code.

Running python files in the terminal also provides more flexibility and control compared to using an IDE, because you can easily modify the arguments passed to the script and execute it from anywhere.

Let us now look at how to do that.

How to run a Python file in a terminal?

Before we get into the step-by-step process, let us first ensure that python is accessible through the terminal. This can be done by just opening the terminal, as explained later in Step 1, and entering the command ‘python’. That should open an interactive python environment that looks something like this:

$ python

 

Output:

Python 3.9.12 (main, Apr  5 2022, 06:56:58)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

 

If this does not happen, that means python is not installed properly. Try reinstalling Python. To exit the interactive python environment, enter the following command or function:

>>> exit()

 

Running a python file in a terminal is a straightforward and simple process. The following step-by-step guide should help you run go through it:

  1. Open the terminal: In Windows, it’s called Command Prompt. You can open Command Prompt by searching it in the start menu or by searching ‘cmd’ instead. Powershell technically has the same exact functionality too. On macOS or Linux, you can open the terminal by searching “Terminal” in Spotlight or in the applications menu.

  2. Navigate to Directory: Once the terminal or the command prompt is open, the next step is to navigate to the directory of the python file. You can do that with the command ‘cd’ followed by the file directory. If the path of the file directory is “C:/User/Documents/PythonPrograms”, you can enter cd C:/User/Documents/PythonPrograms.

  3. Run File in Folder: Now you have to run the python file in the folder. That can be done with the python command or the python3 command depending on the version of python you are using. The python or python3 command followed by the full file name with the file extension will run the python file in the terminal. For example, enter ‘python main.py’ or ‘python3 main.py’ in the terminal.

  4. Pass Arguments: If your python script requires arguments, the arguments can be passed after the ‘python main.py’. For example, if you have to pass two arguments, say arg1 and arg2, then you have to enter the following command, ‘python main.py argument1 arg2’ or ‘python3 main.py arg1 arg2’. 

So, you have successfully run your python script through the terminal. With this knowledge, you can now automate your tasks through the terminal. Here’s an example of a script that you can run in a terminal and it will essentially automate a daily task.

Let's see these steps in detail.

1. Setting Up the Environment

Before you can run Python scripts, you need to have Python installed on your system. Python is available for various operating systems, including Windows, macOS, and Linux. You can download the latest version of Python from the official Python website and follow the installation instructions for your specific operating system.

To create and edit Python files, you'll need a text editor that supports syntax highlighting and code editing features. There are many options available, such as Sublime Text, Atom, Visual Studio Code, and Vim. Choose a text editor that you are comfortable with and suits your workflow.

2. Creating and Opening Python Files

This is how you can create and open Python Files.

Using Vim to Create Python Files: Vim is a powerful and widely used text editor that comes pre-installed on most Unix-based operating systems, including macOS and Linux. To create a Python file using Vim, open a terminal and navigate to the directory where you want to create the file. Then, type the following command:

vim filename.py

 

Press Enter, and Vim will open with an empty file ready for editing. To start inserting text, press the i key to enter insert mode. You can now type your Python code into the file.

Opening Existing Python Files: To open an existing Python file in a text editor, navigate to the directory where the file is located using the terminal. Once you're in the correct directory, type the following command:

vim filename.py

 

Press Enter, and Vim will open the file for editing. You can now view and modify the code as needed.

3. Running Python Files in the Terminal

To run a Python script from the terminal, you need to use the Python interpreter. Open a terminal and navigate to the directory where your Python file is located. Then, type the following command:

python filename.py

 

Press Enter, and the Python interpreter will execute the script. You will see the output of your script displayed in the terminal.

Passing Command Line Arguments:

Python scripts can accept command line arguments, which are values passed to the script when it is executed. To pass command line arguments to your Python script, add them after the script name when running the script. For example:

python filename.py arg1 arg2

 

In this example, arg1 and arg2 are the command line arguments that will be available to your script. You can access these arguments within your script using the sys.argv list.

Automating a Task through the Terminal

Take an example of this simple script that opens Gmail every morning at 10:00 AM.

python: gmail_script.py

import schedule
import webbrowser

def open_gmail():
    Url = 'https:mail.google.com'
    webbrowser.open(url)

schedule.every().day.at("10:00").do(open_gmail)

while True:
    schedule.run_pending()
    time.sleep(1) 

 

You can run this in the terminal with the command “python gmail_script.py” and it will run the file until the terminal is closed and the system is shut down.

Also, learn how to schedule scripts with a task scheduler on windows.

Handling the Issues

There can be multiple issues while doing these processes. Let's see how we can troubleshoot them.

Permission Issues

If you encounter permission issues when running a Python script, it means that the script does not have the necessary permissions to be executed. To fix this issue, you can use the chmod command to change the file permissions and make the script executable. For example:

chmod +x filename.py

 

This command grants execute permission to the owner of the file. After changing the permissions, you should be able to run the script without any issues.

Handling Dependencies

If your Python script depends on external libraries or modules, make sure they are installed on your system before running the script. You can use package managers like pip or conda to install the required dependencies. It's also a good practice to include a requirements.txt file in your project that lists all the dependencies, making it easier for others to install them.

Best Practices

Follow these instructions to make process smoother.

Organizing Your Scripts

As your Python projects grow in size and complexity, it's important to organize your scripts into modules and packages. This helps in maintaining code readability, reusability, and manageability. Divide your code into logical modules based on functionality and group related modules into packages. Use meaningful names for your modules and packages to convey their purpose.

Using Virtual Environments

Virtual environments are isolated Python environments that allow you to manage dependencies and project-specific packages separately from the system-wide Python installation. They provide a clean and reproducible environment for your projects. Use tools like virtualenv or conda to create and activate virtual environments. This ensures that your project remains isolated and doesn't interfere with other Python installations or projects on your system.

Conclusion

With a simple command, we have unlocked a whole new way for python. Running a Python file in a terminal is valuable because it can help you automate tasks but can also help you debug your code and gain more control over executing scripts. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.