Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import keyword is running referenced script

I’m trying to use the import keyword to use a variable from another python script. The problem is that each time I run script_two, it also runs script_one. I only want to run script two. Why is it doing this?

script_two.py:

from script_one import number

print(number)

script_one.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

number = 1

print(number + 1)

>Solution :

You can wrap the print statements in script_one.py to the __main__ block:

script_one.py:

number = 1

if __name__ == "__main__":
    print(number + 1)

script_two.py:

from script_one import number

print(number)

Output:

1

To import the member variables and methods from one module/file to another, it is advised to use methods.

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading