How can I make one Python file run another?


It is not unusual to come across situations in Python coding where you may need one Python script to execute another. Here, in this article, we will discuss and explore four different approaches to perform this task with ease and efficiency. As you will see, you will be guided through each method, helped by step-by-step explanations and real-world code examples. By the end of this article, you'll be armed with the knowledge of various techniques to run Python files from within your code. Let us get started on this exciting journey of executing scripts in Python!

Understanding Python Script Execution

Before we begin discussing the code examples, let us pause for a moment to comprehend the process of executing a Python file from another. Python offers several methods to achieve this task; it empowers you to execute specific scripts based on your project's needs and requirements. It does not matter if you are building complex applications or automating tasks; in either case, these techniques come are very helpful when you need seamless interactions between Python scripts.

Making Use of os.system()

In the very first example the utilization of os.system() is done so as to run another Python file.

In this code snippet, the os module is imported first. The execute_python_file() method takes file_path as its argument; this represents the path of the required Python file that is to be run. We make use of the os.system() function to execute the specified Python file using the 'python' command. A befitting error message is shown in the event that the file cannot be located.

Example

import os

def execute_python_file(file_path):
   try:
      os.system(f'python {file_path}')
   except FileNotFoundError:
      print(f"Error: The file '{file_path}' does not exist.")

The os.system function gives as output the exit code of the command executed. However, in this current implementation, it is found that the function does not return anything.

Using subprocess.run()

This particular example illustrates the usage of subprocess.run() for Python script execution.

Here, we import the subprocess module; this module provides more advanced process handling capabilities than os.system(). The file_path is taken as parameter by the execute_python_file() function, as seen in the earlier example. We then make use of subprocess.run() to execute the Python file indicated by file_path. The command is given as a list of arguments, with "python" as the first element and the Python file's path as the second. In the event that the document isn't found, a proper error message is shown.

It is better to use subprocess.run() or subprocess.Popen() with proper arguments to execute commands safely.

It is helpful to capture and return the exit code or any other output from the executed Python file if required.

Here the function uses subprocess.run() for executing the Python file and capturing the output:

With this implementation, it will empower you to execute the Python file as well as capture both the standard output and standard error of the executed script.

Example

import os
import subprocess

def execute_python_file(file_path):
   try:
      completed_process = subprocess.run(['python', file_path], capture_output=True, text=True)
      if completed_process.returncode == 0:
         print("Execution successful.")
         print("Output:")
         print(completed_process.stdout)
      else:
         print(f"Error: Failed to execute '{file_path}'.")
         print("Error output:")
         print(completed_process.stderr)
   except FileNotFoundError:
      print(f"Error: The file '{file_path}' does not exist.")

file_path = '/content/fubar.py'
execute_python_file(file_path)

Output

For a certain file, the following was the output

Execution successful.
Output:
Hi

Using exec()

In this example code, we introduce the exec() function for executing the Python script.

Here, we deploy the built-in exec() function for the execution of the Python code present in the specified file. The execute_python_file() function takes file_path as its argument; file_path is the path of the Python file that you wish to run. We open the file in read mode using open() and its content is read into the python_code variable. Then, we pass python_code to exec() as an argument to execute the Python script. In the event the file is not found, a corresponding error message is shown.

Example

def execute_python_file(file_path):
   try:
      with open(file_path, 'r') as file:
         python_code = file.read()
         exec(python_code)
   except FileNotFoundError:
      print(f"Error: The file '{file_path}' does not exist.")
file_path ='/content/foo.py'

execute_python_file(file_path)      

Output

For certain file foo.py, the following was the output

Lorem Ipsum

Using importlib.import_module()

For our last example, we begin by making use of importlib.import_module() to run a Python file.

In this snippet, we import the importlib module; this module makes available utilities for working with other modules. The file_path is taken as a parameter by the execute_python_file() function; it represents the path of the desired Python file. We deploy importlib.import_module() to import the specified Python file as a module. If it so happens that the file is not found, an appropriate error message is notified.

Example

import importlib

def execute_python_file(file_path):
   try:
      module_name = file_path.replace('.py', '')  # Remove the '.py' extension
      module = importlib.import_module(module_name)
   except FileNotFoundError:
      print(f"Error: The file '{file_path}' does not exist.")
   except ModuleNotFoundError:
      print(f"Error: The module '{module_name}' could not be found.")
   except ImportError as e:
      print(f"Error: Unable to import '{module_name}': {e}")

Python offers various approaches to execute one Python file from another, each with its unique advantages and use cases. Depending on whether you prefer os.system(), subprocess.run(), exec(), or importlib.import_module(), you have a range of options at your disposal to carry out the task of executing one Python file from another.

As you proceed along your Python journey, consider the specific requirements of your project when selecting the most befitting method for script execution. Utilize the flexibility and power of Python to effortlessly interact with different components of your code.

Updated on: 02-Sep-2023

50K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements