Skip to content

Running Python File in Terminal: Step-by-Step Guide

[

How to Run Your Python Scripts and Code

A Python script or program is a file containing executable Python code. Being able to run Python scripts and code is probably the most important skill that you need as a Python developer. By running your code, you’ll know if it works as planned. You’ll also be able to test and debug the code to fix errors and issues. Ultimately, you write code in order to run it and accomplish tasks.

In this tutorial, you’ll learn about some of the techniques for running Python scripts and code. The technique that you’ll use in each situation will depend on your environment, platform, needs, and skills.

What Scripts and Modules Are

In computing, the term script refers to a text file containing a logical sequence of orders that you can run to accomplish a specific task. These orders are typically expressed in a scripting language, which is a programming language that allows you to manipulate, customize, and automate tasks.

Scripting languages are usually interpreted at runtime rather than compiled. So, scripts are typically run by some kind of interpreter, which is responsible for executing the instructions and producing the desired output.

Python scripts are no exception. When you run a Python script, the interpreter reads the code line by line and performs the specified actions. Scripts can be simple, consisting of a few lines of code, or complex, containing dozens or even hundreds of lines.

Apart from scripts, Python also uses the concept of modules. A module is a self-contained file containing Python code that defines variables, functions, and classes. Modules are used to organize code into logical units, making it easier to manage and reuse.

How to Run Python Scripts From the Command Line

The command line or terminal is a text-based interface used to interact with the operating system. It allows you to execute commands and run programs, including Python scripts. There are several ways to run Python scripts from the command line.

Using the python Command

The most basic and common way to run a Python script from the command line is to use the python command followed by the name of the script file. For example, if your script is named script.py, you would run it like this:

python script.py

This command tells the python interpreter to execute the code in the script.py file. The output of the script will be displayed in the terminal.

Using the Script’s Filename Directly

In some cases, you may have a Python script that has the appropriate shebang line #!/usr/bin/env python at the beginning. This line tells the operating system which interpreter to use when executing the script. With the shebang line present and the script file set as executable, you can run the script by typing its filename directly. For example:

./script.py

In this case, the ./ indicates that the script file is in the current directory.

Running Modules With the -m Option

Python allows you to run modules directly using the -m option. This is particularly useful when you want to execute a module that is not the main entry point of the program. To run a module, you would use the following command:

python -m module_name

Replace module_name with the name of the module you want to run. The module must be importable, meaning that it should be in a directory included in Python’s module search path.

How to Run Python Code Interactively

Apart from running Python scripts, you can also execute Python code interactively using the Python interpreter. This is often referred to as running code in the REPL (Read-Eval-Print Loop).

Getting to Know the Python Interpreter

The Python interpreter is a command-line program that allows you to enter Python code and see the results immediately. It provides a convenient way to experiment and test code snippets without the need for a separate script file.

To start the Python interpreter, open the command line or terminal and type python. You will see the Python prompt, indicated by the >>> symbol. This is where you can enter Python code and have it executed.

Running Python Code Interactively

To run Python code interactively, simply type the code at the Python prompt and press Enter. The interpreter will immediately execute the code and display the result, if any.

For example, to calculate the sum of two numbers, you can enter the following code:

>>> num1 = 4
>>> num2 = 5
>>> sum = num1 + num2
>>> sum
9

In this example, the code assigns the values 4 and 5 to the variables num1 and num2, respectively. It then calculates their sum and assigns the result to the variable sum. Finally, it displays the value of sum, which is 9.

How to Run Scripts From Python Code

Python provides several ways to run scripts directly from other Python code. These methods allow you to execute external Python files and incorporate their functionality into your program.

Taking Advantage of import Statements

One way to run a Python script from another Python program is by using the import statement. This statement allows you to load and execute the code in another Python file as a module.

To run a script using the import statement, you would include the following line in your code:

import script

Replace script with the name of the Python file you want to run. The script must be in the same directory or a directory included in Python’s module search path.

After importing the script, you can access its functions, variables, and classes just like you would with any other module. For example, if the script defines a function called calculate_sum, you can call it in your code like this:

import script
result = script.calculate_sum(4, 5)
print(result)

In this example, the calculate_sum function in the script module is called with the arguments 4 and 5. The result is then printed to the console.

Using the importlib Standard-Library Module

Python’s importlib module provides a more flexible way to run Python scripts dynamically. This module allows you to load and execute modules at runtime, giving you more control over the importing process.

To run a script using the importlib module, you would use the following code:

import importlib
module = importlib.import_module('script')

Replace script with the name of the Python file you want to run. The file must be in a directory included in Python’s module search path.

Once loaded, you can access the functions, variables, and classes in the module just like any other module. For example, if the script defines a function called calculate_sum, you can call it like this:

result = module.calculate_sum(4, 5)
print(result)

In this example, the calculate_sum function in the module object is called with the arguments 4 and 5. The result is then printed to the console.

Leveraging the Power of the Built-in exec() Function

The exec() function in Python allows you to execute arbitrary Python code dynamically. It takes a string containing the code as an argument and executes it.

To run a script using the exec() function, you would construct a string containing the code and pass it to exec(). For example:

with open('script.py') as f:
code = f.read()
exec(code)

In this example, the script file script.py is opened and its contents are read. The code is then passed to exec() for execution.

Note that using the exec() function can be risky, as it allows the execution of arbitrary code. It is important to ensure that the code being executed is safe and trusted.

How to Run Python Scripts on IDEs and Code Editors

Integrated Development Environments (IDEs) and code editors provide powerful tools for writing, running, and debugging code. Most modern IDEs and code editors have built-in support for running Python scripts.

To run a Python script in an IDE or code editor, you would typically open the script file, then look for a run button or menu option. Clicking the run button or selecting the run option will execute the script and display the output.

The exact steps may vary depending on the specific IDE or code editor you are using. Refer to the documentation or help resources for your chosen tool for more information on how to run Python scripts.

How to Run Python Scripts From a File Manager

Some operating systems allow you to run Python scripts directly from the file manager or file explorer. This can be convenient if you want to quickly execute a script without opening a command line or IDE.

To run a Python script from a file manager, you would typically navigate to the location of the script file, then double-click on the file. The operating system will detect that the file is a Python script and execute it using the default Python interpreter.

This method is suitable for running simple scripts that do not require any user input or interaction. If your script requires command-line arguments or displays output, it may not work as expected when run from a file manager.

Conclusion

Running Python scripts and code is an essential skill for any Python developer. In this tutorial, you learned various methods for running Python scripts from the command line, interactively in the Python interpreter, from other Python code, as well as on IDEs, code editors, and file managers. Choose the method that best suits your needs and environment, and start running your Python scripts with confidence.

Now that you know how to run your Python scripts and code, you’re ready to take on more complex projects and explore the vast possibilities of Python programming. Happy coding!