How to Run One Python Script From Another

In this short guide, you’ll see how to run one Python script from another Python script.

Steps

Step 1: Place the Python Scripts in the Same Folder

To start, place your Python scripts in the same folder.

For example, assume that two Python scripts (called python_1 and python_2) are stored in the same folder:

python_1
python_2

The ultimate goal is to run the python_2 script from the python_1 script.

Step 2: Add the Syntax

Next, add the syntax to each of your scripts.

For instance, add the following syntax to the python_1 script:

import python_2

print("what are you up to?")

Where:

  • The first line of “import python_2” in the python_1 script, would call the second python_2 script
  • The second line of the code simply prints the expression of “what are you up to?”

Now add the syntax to the python_2 script:

print("hello world")

In this case, the expression of “hello world” would be printed when running the second script.

Step 3: Run One Python Script From Another

Finally, run the python_1 script.

Notice that the results from the python_2 script would be displayed first, and then the results from the python_1 script:

hello world
what are you up to?

Call a Specific Variable from One Python Script to Another

Now you’ll see how to call a specific variable (called “x”) from the python_2 script to the python_1 script.

In that case, edit the syntax in the python_1 script to the following:

import python_2 as p2

print(p2.x)

Then, assign a value (e.g., “hello world”) to the “x” variable in the python_2 script:

x = "hello world"

Finally, run the python_1 script:

hello world

Interaction of Variables from the Two Scripts

In the final section of this guide, you’ll see how variables from the two scripts could interact by summing them together.

First, modify the syntax in the python_1 script to the following:

import python_2 as p2

y = 2

print(p2.x + y)

Then, change the syntax in the python_2 script to:

x = 5

Finally, run the python_1 script, and you’ll get “7” which is indeed the sum of the two variables:

7

2 thoughts on “How to Run One Python Script From Another”

  1. I’m not sure where you’re getting your info, but good topic.

    Reply

Leave a Comment