0

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)
Alditrus
  • 87
  • 1
  • 5
  • 1
    importing runs the file, how else would it know what stuff does? you can't change that behaviour, you can, however, use `if __name__ == '__main__':` to limit what is executed when importing and when not importing – Matiiss Jan 03 '22 at 01:34
  • 1
    That's what an import does. Voting to close as it's unclear what you're asking... – wim Jan 03 '22 at 01:34
  • Because in your `script_two`, *you* run the other one when you do `from script_one import number` – juanpa.arrivillaga Jan 03 '22 at 01:52

1 Answers1

2

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:

arshovon
  • 13,270
  • 9
  • 51
  • 69