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...
1 Answers
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

- 35,554
- 7
- 89
- 134