Run One Python Script From Another in Python - GeeksforGeeks (2024)

Last Updated : 16 Sep, 2024

Summarize

Comments

Improve

In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the same process. In this article, we will explore all the specified approaches to make one Python file run another.

Run One Python Script From Another in Python

Below are some of the ways by which we can make one Python file run another in Python:

  • Using import Statement
  • Using exec() Function
  • Using subprocess Module
  • Using os.system() Function

Make One Python File Run Another Using Import Module

In this example, file_2.py imports functions from file_1.py using the import statement. By calling the imported function in file_2.py (file_1.printing()), the code executes the printing() function defined in file_1.py, allowing for the integration and execution of code from one file within another.

Python
# file_1.py# creating functiondef printing(): print("Hello world!")
Python
# file_2.py# importing file_1import file_1# calling function of file_1.py form file_2.pyfile_1.printing()

Output:
Run One Python Script From Another in Python - GeeksforGeeks (1)

Run One Python Script From Another Using exec() Function

In this example, file_2.py opens and reads the file_1.py, by ‘with‘ statement using the ‘open‘ function it opens file_1.py, and the ‘read‘ function reads the file_1.py. The code read from file_1.py will be executed by using the exec() function within file_2.py.

Python
# file_1.py# printing hello world!print("Hello world!")
Python
# file_2.py# opening file_1.py and reading it with read() and executing if with exec()with open("file_1.py") as file: exec(file.read())

Output:

Run One Python Script From Another in Python - GeeksforGeeks (2)

Python Run One Script From Another Using subprocess Module

In this example, file_2.py imports the subprocess module using the import statement. By using run() function Python script in “file_1.py” will be executed as a separate process within file_2.py.

Python
# file_1.py# printing This is file_1 content.print("This is file_1 content.")
Python
# file_2.py# importing subprocess module import subprocess# running other file using run()subprocess.run(["python", "file_1.py"])

Output:

Run One Python Script From Another in Python - GeeksforGeeks (3)

Run One Python Script From Another Using os.system() Function

In this example, file_2.py imports the os module using the import statement. Then using os.system() to execute the command “python file_1.py” and file_1.py will run within the same process but in a separate system shell.

Python
# file_1.py# printing This is file_1 content.print("This is file_1 content.")
Python
# file_2.py# importing os moduleimport os# running other file using run()os.system("python file_1.py")

Output:

Run One Python Script From Another in Python - GeeksforGeeks (4)

Conclusion

In conclusion, understanding how to make one Python file run another is a useful skill for writing organized and modular code. Using the import statement and grasping the concept of modules allows for improved code reusability. Incorporating functions and classes enhances the structure and readability of your code. Remembering to organize files and follow naming conventions is essential for a collaborative development process. In essence, mastering these techniques helps you create well-structured and scalable Python applications.

Run One Python Script From Another in Python – FAQs

How to Run a Python Script from Another Python Script

You can run a Python script from another Python script in several ways, depending on what suits your needs:

  1. Using exec() Function: This function can execute a script contained within a string or file.
  2. Using import: If the script is a module, you can import functions or classes and then call them.
  3. Using subprocess Module: This method allows you to run the script as a separate process.

filename = ‘script2.py’
with open(filename) as file:
exec(file.read())

import script2
script2.main() # Assuming there’s a function named ‘main’ in script2.py

import subprocess
subprocess.run([‘python’, ‘script2.py’])

How Do I Run a Python Script with a Different Version of Python?

To run a Python script using a specific version of Python, especially if multiple versions are installed on your system, you can specify the Python interpreter you want to use:

python3.8 script.py # For Unix/Linux/Mac
py -3.8 script.py # For Windows, if using Python Launcher

How to Combine Two Python Scripts to Run as One Program

To combine two Python scripts into one program, you can refactor them to function as modules. Import necessary functions or classes from one script into another:

  1. Modify both scripts to include functions: Wrap the code in each script in functions.
  2. Main script calls functions from both: In your main script, import these functions and call them.

from script1 import function1
from script2 import function2

function1()
function2()

How Do I Connect Two Python Scripts?

Connecting two Python scripts typically involves making one script a module from which the other script imports functionality:

  1. Turn one script into a module: Ensure the script has functions that can be imported.
  2. Import and use functions or classes from one script to another:

# In your main script
from other_script import some_function
result = some_function()

How Do I Make a Python Script Executable on Another Computer?

To make a Python script executable on another computer:

  1. Ensure Python is Installed: The target machine needs to have Python installed, or you can create an executable using tools like PyInstaller.
  2. Write a Shebang Line: At the top of your script, add #!/usr/bin/env python3 to indicate which interpreter to use.
  3. Change File Permission (Unix/Linux/Mac): Make the script executable.
  4. Create a Standalone Executable:
    • Use PyInstaller:This command creates a standalone executable that can be run without needing Python installed on the target system.

chmod +x script.py

pip install pyinstaller
pyinstaller –onefile script.py



    R

    ramlakhan7

    Run One Python Script From Another in Python - GeeksforGeeks (5)

    Improve

    Next Article

    How to Run Another Python script with Arguments in Python

    Please Login to comment...

    Run One Python Script From Another in Python - GeeksforGeeks (2024)
    Top Articles
    The 5 "R's"​ Mental Health Matters
    What Is the Google Sheets Row Limit: Navigating the Depths of Data | WPS Office Blog
    Jack Doherty Lpsg
    WALB Locker Room Report Week 5 2024
    Bleak Faith: Forsaken – im Test (PS5)
    Repentance (2 Corinthians 7:10) – West Palm Beach church of Christ
    Missing 2023 Showtimes Near Cinemark West Springfield 15 And Xd
    Es.cvs.com/Otchs/Devoted
    Is Sportsurge Safe and Legal in 2024? Any Alternatives?
    What is international trade and explain its types?
    Nyuonsite
    T&G Pallet Liquidation
    FIX: Spacebar, Enter, or Backspace Not Working
    Full Range 10 Bar Selection Box
    Craigslist Pikeville Tn
    Binghamton Ny Cars Craigslist
    Meritas Health Patient Portal
    Spartanburg County Detention Facility - Annex I
    Craigslist Malone New York
    Transfer and Pay with Wells Fargo Online®
    Race Karts For Sale Near Me
    Healthier Homes | Coronavirus Protocol | Stanley Steemer - Stanley Steemer | The Steem Team
    Panic! At The Disco - Spotify Top Songs
    Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
    Helpers Needed At Once Bug Fables
    Inter Miami Vs Fc Dallas Total Sportek
    Wrights Camper & Auto Sales Llc
    Cor Triatriatum: Background, Pathophysiology, Epidemiology
    Wku Lpn To Rn
    Stephanie Bowe Downey Ca
    Sinfuldeed Leaked
    Craigs List Jax Fl
    Mosley Lane Candles
    UPC Code Lookup: Free UPC Code Lookup With Major Retailers
    Utexas Baseball Schedule 2023
    What Time Does Walmart Auto Center Open
    School Tool / School Tool Parent Portal
    Reborn Rich Ep 12 Eng Sub
    Mta Bus Forums
    Td Ameritrade Learning Center
    craigslist | michigan
    Cranston Sewer Tax
    18 terrible things that happened on Friday the 13th
    Panorama Charter Portal
    Danielle Ranslow Obituary
    Miami Vice turns 40: A look back at the iconic series
    House For Sale On Trulia
    Craigslist Sarasota Free Stuff
    Elvis Costello announces King Of America & Other Realms
    Cvs Minute Clinic Women's Services
    Jovan Pulitzer Telegram
    Latest Posts
    Article information

    Author: Edwin Metz

    Last Updated:

    Views: 6378

    Rating: 4.8 / 5 (78 voted)

    Reviews: 93% of readers found this page helpful

    Author information

    Name: Edwin Metz

    Birthday: 1997-04-16

    Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

    Phone: +639107620957

    Job: Corporate Banking Technician

    Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

    Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.