0

Is it possible to import a Python script into a main script and then just use the variables? I don't want the other script to execute inside of the main script, just attach one of the variables...

Blue
  • 27
  • 5
  • 4
    `from script import var` – iBug Jan 31 '18 at 16:13
  • Importing another script executes it. Whether than has unwanted effects depends on how the script is written (whether it uses an `if __name__=='__main__'` block appropriately). – khelwood Jan 31 '18 at 16:16

1 Answers1

1

If you can edit the script being imported, there's a solution:

Put all the executed code into a block starting with

if __name__ == '__main__':

In this way, the code in the if block above will be executed only if the script is run directly. i.e. when you run python script.py.

You can import only the variable like this:

from script import var

If you want to import the variable without going through the whole script, then as per Python's design it's not possible. import will always go through the whole script being imported, and will avoid whatever that's inside __name__ == '__main__'.

You have an option to read the script file and find the variables, then do it yourself by parsing and executing it, but IMO that's unnecessary job to do since you have import.

You can see the answers under Python: import module without executing script

iBug
  • 35,554
  • 7
  • 89
  • 134