Table of contents
1.
Introduction
2.
What Scripts and Modules Are?
3.
How to Run Python Scripts From the Command Line?
3.1.
Using the python Command
3.2.
Example
3.3.
Using the Script’s Filename Directly
3.4.
Running Modules With the -m Option
4.
How to Run Python Code Interactively?
4.1.
Getting to Know the Python Interpreter
4.2.
Running Python Code Interactively
5.
How to Run Scripts From Python Code?
5.1.
Taking Advantage of import Statements
5.2.
Using the importlib Standard-Library Module
5.3.
Leveraging the Power of the Built-in exec() Function
6.
How to Run Python Scripts on IDEs and Code Editors?
7.
How to Run Python Scripts From a File Manager?
8.
Frequently Asked Questions
8.1.
What are the different ways to run a Python script in Linux?
8.2.
What is the Python interactive shell, and how do I use it?
8.3.
How can I run Python scripts using a file manager in Linux?
9.
Conclusion
Last Updated: Dec 20, 2024
Easy

How to Execute Python Script in Linux

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python is a popular programming language used for various applications, from web development to data analysis. Running Python scripts in Linux is quite easy process that can be done through the command line or using IDEs and code editors. 

How to Execute Python Script in Linux

In this article, we will discuss different methods to execute Python scripts in Linux, including using the command line, IDEs, and file managers. 

What Scripts and Modules Are?

Before running Python scripts, it's important to understand what a script and a module are:

  • Python Script: A Python script is simply a file that contains Python code. The code is written in a .py file extension, and the script can be executed to perform a particular task or set of tasks.
     
  • Module: A Python module is a file containing Python definitions and statements. It allows you to organize code into reusable components. You can run Python code in a script or use it as part of a module by importing it into other scripts.

How to Run Python Scripts From the Command Line?

Linux provides several ways to execute Python scripts directly from the command line. Let’s look at the most common methods.

Using the python Command

If you want to run a Python script from the command line, the first thing to do is open the terminal.

First, navigate to the directory where your Python script is located using the cd command. For example:

cd /path/to/your/script

 

Once you're in the right directory, use the python command (or python3 for newer versions of Python) followed by the script name:

python3 my_script.py


This command will execute the script and display the output in the terminal.

Example

Let’s say your script my_script.py contains the following code:

print("Hello, world!")
You can also try this code with Online Python Compiler
Run Code


Running the command will output:

Hello, world!

Using the Script’s Filename Directly

In Linux, you can also execute Python scripts directly by making the script executable. First, ensure that your script has the correct permissions and a shebang at the top.

Add the shebang to your script to tell Linux how to interpret the script:

#!/usr/bin/env python3
print("Hello, world!")


Make the script executable using chmod:

chmod +x my_script.py


Now, you can run the script directly:

./my_script.py


This will also display:

Hello, world!

Running Modules With the -m Option

The -m option in Python allows you to run a module as a script. This is useful for running built-in modules or scripts you’ve created.

For example, to run the http.server module (a built-in module in Python) to start a simple web server:

python3 -m http.server


This will run the server, and you’ll see output like:

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

How to Run Python Code Interactively?

Sometimes, you may want to execute Python code interactively to test small snippets or experiment. You can use the Python interpreter in interactive mode.

Getting to Know the Python Interpreter

The Python interpreter allows you to type Python commands directly in the terminal. To start an interactive session, simply type python3 in the terminal:

python3


Once the interpreter starts, you can type Python code line by line. For example:

>>> print("Hello, Python!")
You can also try this code with Online Python Compiler
Run Code


Output

Hello, Python!


This is an excellent way to quickly test simple commands or explore Python functions.

Running Python Code Interactively

Within the interactive mode, you can run multiple lines of code and even define functions. For example:

>>> def greet(name):
>>>    print(f"Hello, {name}!")


>>> greet("Alice")
You can also try this code with Online Python Compiler
Run Code

 

Output

Hello, Alice!


This approach is helpful when you want to check the behavior of certain functions or write code snippets without creating a script.

How to Run Scripts From Python Code?

You might sometimes need to execute other Python scripts from within a Python script. There are several ways to do this.

Taking Advantage of import Statements

The simplest way to run another Python script from within your script is by using the import statement. When you import a script or module, Python runs the code in that script.

For example:

# my_script.py
import another_script

# Contents of another_script.py
print("This is another script.")


This method will execute the contents of another_script.py as soon as it's imported.

Using the importlib Standard-Library Module

For more advanced script loading and execution, Python provides the importlib module. This allows you to import and run modules programmatically. Here's how you can use it:

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


This method is flexible and useful if you need to dynamically load modules at runtime.

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

Another way to execute Python code from within a script is by using the exec() function. This function takes a string containing Python code and executes it.

Example:

code = "print('Hello from exec!')"
exec(code)
You can also try this code with Online Python Compiler
Run Code


This will output:

Hello from exec!


However, exec() should be used carefully, as it can execute arbitrary code and might introduce security risks.

How to Run Python Scripts on IDEs and Code Editors?

Linux offers a wide range of IDEs & code editors that make it easy to execute Python scripts. Popular options include PyCharm, Visual Studio Code, & IDLE. These tools provide features like syntax highlighting, debugging, & integrated terminals, making the development process more efficient.

To run a Python script using an IDE or code editor, follow these general steps:

  • Open the IDE or code editor of your choice.
  • Create a new file or open an existing Python script.
  • Write or modify the Python code as needed.
  • Save the file with a ".py" extension.
  • Use the IDE's built-in run or execute command to run the script. This is usually done by clicking a "Run" button or pressing a keyboard shortcut like "Ctrl+F5" or "Shift+F10", depending on the IDE.
     

For example, in Visual Studio Code:

  • Open Visual Studio Code.
  • Create a new file named "example.py".
  • Write your code: Example- print("Hello, World!")
  • Save the file.
  • Press "Ctrl+F5" or select "Run" from the menu to execute the script.

The output will appear in the integrated terminal within Visual Studio Code.

How to Run Python Scripts From a File Manager?

In Linux, you can also run Python scripts directly from a file manager. This method is useful when you want to quickly execute a script without opening a terminal or an IDE. Most Linux file managers, such as Nautilus (default in GNOME) & Dolphin (default in KDE), support this feature.

To run a Python script from a file manager:

  • Open your preferred file manager & navigate to the directory where the Python script is located.
  • Locate the Python script file with the ".py" extension.
  • Double-click on the file to open it.
  • A dialog box will appear, asking you how you want to run the script. Select "Run in Terminal" or "Execute" to run the script in a terminal window.

 

Alternatively, you can make the Python script executable & run it directly:

  • Right-click on the Python script file & select "Properties".
  • Go to the "Permissions" tab.
  • Check the box next to "Allow executing file as program" to make the script executable.
  • Close the properties window.
  • Double-click on the script file to run it directly.

 

For example, let's say you have a script named "hello.py" on your desktop:

  • Open the file manager & navigate to the desktop.
  • Locate the "hello.py" file.
  • Double-click on the file & select "Run in Terminal" or make it executable & double-click to run.


The script will be executed, & the output will be displayed in a terminal window or a pop-up dialog, depending on the script's content.

Frequently Asked Questions

What are the different ways to run a Python script in Linux?

You can run a Python script in Linux by using the python command in the terminal, running the script’s filename directly, or using the -m option for modules. You can also execute scripts interactively or programmatically from within other Python code.

What is the Python interactive shell, and how do I use it?

The Python interactive shell allows you to execute Python code line by line in a terminal. By typing python3 in your terminal, you can enter the shell where you can test small code snippets, explore Python functions, or debug your code without needing to create a full script. It’s a great tool for experimenting with Python commands in real-time.

How can I run Python scripts using a file manager in Linux?

You can run Python scripts directly from a file manager in Linux by right-clicking on the script file and selecting the option to "Open with Python" (this may vary depending on your file manager). Make sure the script has the proper execution permissions by running chmod +x script_name.py in the terminal. 

Conclusion

In this article, we've discussed multiple ways to execute Python scripts in Linux, from the command line to IDEs and interactive Python sessions. Whether you prefer using the terminal, executing scripts from within other Python code, or working within an IDE, there are plenty of options available to run your Python scripts efficiently. By understanding these methods, you can choose the one that best fits your workflow and project needs.

Live masterclass