Import keyword is running referenced script
Question:
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:
number = 1
print(number + 1)
Answers:
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:
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:
number = 1
print(number + 1)
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: