How to link two Python scripts between each other

Linking Python files with each other is a very good way to organize your code and not end up with hundreds of lines of classes and functions.

In this short article, my aim is going to show you how to simply use functions you created in one .py file in an other file without having to rewrite them.

Let’s create a Script1.py file that will contain a function called functionOne.

As you can see, this function requires an integer that will be ran against the equation “If variable is greater than 10 print X, else print Y”.

Now, let’s create a second file called Script2.py

Now, when we run our script inside of our Terminal, this is the result:

And this is it. Despite having no mention of the function functionOne, our Script2.py is able to find the function in Script1.py and execute it.

The only thing you have to do is to write:

from Script1 import *

This basically is asking the .py file of destination to look for a file called Script1.py and import all of the functions that are present inside of the document.

In the event that you do not want to import all of the functions present in your source document, you could also write this:

from Script1 import functionOne

This ensures that you only import the function that you plan on actually using and keep your code clean and understandable.

As I said, this was a short article but I believe it will be helpful :). As always, if you have any questions, I will answer any questions you may have in the comments section down below so feel free to shoot!

Until next time,

Yaniss Illoul

Share on reddit
Share on facebook
Share on twitter
Share on linkedin
Share on print

You might also like these posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

function external_link_attribute() { ?>

more!

Tutorials, Case Studies, Content Curation, …

In your inbox, once a week.

more!

Tutorials, Case Studies, Content Curation, …

In your inbox, once a week.