Skip to content

Running Python Script in Python: Step-by-Step Guide

[

How to Run Your Python Scripts and Code

Table of Contents

  • What Scripts and Modules Are
  • How to Run Python Scripts From the Command Line
    • Using the python Command
    • Using the Script’s Filename Directly
    • Running Modules With the -m Option
  • How to Run Python Code Interactively
    • Getting to Know the Python Interpreter
    • Running Python Code Interactively
  • How to Run Scripts From Python Code
    • Taking Advantage of import Statements
    • Using the importlib Standard-Library Module
    • Leveraging the Power of the Built-in exec() Function
  • How to Run Python Scripts on IDEs and Code Editors
  • How to Run Python Scripts From a File Manager
  • Conclusion

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 code line by line.

In Python, a script is also known as a module. A Python module is a file containing Python code that you can import and use in other scripts or modules. Modules allow you to split your code into smaller, logical units that are easier to manage and reuse.

How to Run Python Scripts From the Command Line

Using the python Command

The most common way to run Python scripts is by using the python command in the command line or terminal. To run a script, you simply need to open a command line or terminal window, navigate to the directory where the script is located, and use the following command:

python script.py

Where script.py is the name of your Python script file.

Using the Script’s Filename Directly

In some cases, you may be able to run a Python script by simply typing the name of the script file in the command line or terminal, without using the python command. This method works if the script has the correct file permissions and includes a shebang line, which tells the operating system the path to the interpreter that should be used to execute the script.

To run a script using this method, navigate to the directory where the script is located and type the following command:

./script.py

Where script.py is the name of your Python script file.

Running Modules With the -m Option

Another way to run Python scripts is by using the -m option followed by the name of the module you want to run. This method is useful when you want to execute a module directly without creating a separate script file.

To run a module using this method, open a command line or terminal window, navigate to the directory where the module is located, and use the following command:

python -m module_name

Where module_name is the name of your Python module.

How to Run Python Code Interactively

Getting to Know the Python Interpreter

The Python interpreter is a program that reads your Python code and executes it line by line. It provides a way to interact with your code in real-time, allowing you to experiment, test, and debug your code interactively. The Python interpreter provides a Read-Eval-Print Loop (REPL), which allows you to enter Python code directly and see the results immediately.

To start the Python interpreter, open a command line or terminal window and type the following command:

python

This will open the Python interpreter and display the Python prompt (>>>), indicating that the interpreter is ready to accept your code.

Running Python Code Interactively

Once you’re inside the Python interpreter, you can enter Python code directly and see the results immediately. This is a great way to test and debug small pieces of code or to experiment with new features and concepts.

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

Here’s an example of running Python code interactively:

>>> x = 10
>>> y = 5
>>> z = x + y
>>> print(z)
15

In this example, we create three variables (x, y, and z), perform a simple addition operation, and print the result. The Python interpreter executes each line of code as we enter it and displays the result immediately, allowing us to see the output in real-time.

How to Run Scripts From Python Code

Taking Advantage of import Statements

In Python, scripts and modules can be run from other scripts or modules by using the import statement. This allows you to reuse existing code and organize your code into logical units.

To run a script or module from another script or module, you can use the import statement followed by the name of the script or module (without the .py extension). You can then call the functions, classes, or variables defined in the imported code.

Here’s an example of running a script from another script using the import statement:

script1.py
def hello():
print("Hello, World!")
# script2.py
import script1
script1.hello()

In this example, we create two scripts (script1.py and script2.py). script1.py defines a hello() function, and script2.py imports script1 and calls the hello() function. When we run script2.py, it will execute the code in script1.py and print “Hello, World!“.

Using the importlib Standard-Library Module

Python also provides the importlib module, which allows you to import and run code dynamically at runtime. This can be useful when you need to load and run a script or module based on user input or configuration settings.

To use the importlib module to run a script or module dynamically, you can use the import_module() function followed by the name of the script or module (as a string). You can then call the functions, classes, or variables defined in the imported code.

Here’s an example of using the importlib module to run a script dynamically:

import importlib
module_name = "script"
module = importlib.import_module(module_name)
module.hello()

In this example, we use the importlib module to import and run a script or module specified by the module_name variable. We call the hello() function defined in the imported code and execute it.

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

Python provides the built-in exec() function, which allows you to execute arbitrary Python code dynamically at runtime. This can be useful when you need to run scripts or code stored as strings, or when you want to execute code based on user input or configuration settings.

To use the exec() function to run Python code dynamically, you can simply pass the code as a string to the exec() function. The code will be executed line by line, just like when running a script or module.

Here’s an example of using the exec() function to run Python code dynamically:

code = """
x = 10
y = 5
z = x + y
print(z)
"""
exec(code)

In this example, we define a code string that contains Python code. We then use the exec() function to execute the code stored in the code variable. The code is executed line by line, and the result (the sum of x and y) is printed.

How to Run Python Scripts on IDEs and Code Editors

Most popular IDEs and code editors for Python provide built-in features to run and execute Python scripts directly from the interface. These features often include buttons or shortcuts that allow you to run the current script or selected code without leaving the IDE or code editor.

To run a Python script on an IDE or code editor, you typically need to open the script in the editor, and then use the provided features to run the script. The specific steps may vary depending on the IDE or code editor you are using, so you should consult the documentation or help resources for your specific tool.

Some popular Python IDEs and code editors with built-in features for running Python scripts include:

  • PyCharm
  • Visual Studio Code
  • Atom
  • Sublime Text

How to Run Python Scripts From a File Manager

In addition to running Python scripts from the command line or IDEs, you can also run Python scripts directly from your operating system’s file manager. This can be useful when you want to quickly execute a script without opening a command line or IDE.

To run a Python script from a file manager, you typically need to follow these steps:

  1. Locate the script file in the file manager.
  2. Right-click on the script file to open the context menu.
  3. Look for an option that allows you to run or execute the script. The name of this option may vary depending on your operating system and file manager.
  4. Click on the run or execute option to run the script.

The exact steps and options may vary depending on your operating system and file manager. You should consult the documentation or help resources for your specific operating system and file manager for more information.

Conclusion

Running Python scripts and code is a fundamental skill that every Python developer should have. Whether you’re running scripts from the command line, executing code interactively, or running scripts from other scripts, knowing how to execute Python code is essential for testing, debugging, and accomplishing tasks.

In this tutorial, you’ve learned various techniques for running Python scripts and code in different environments and scenarios. You’ve explored how to run scripts from the command line, execute code interactively, run scripts from other scripts, and even run scripts from file managers.

By mastering these techniques, you’ll have the knowledge and skills to effectively run your Python scripts and code, allowing you to develop and execute your Python projects with confidence.