2
votes

More specifically, I have a file

file file1.py:

if __name__ == '__main__':
    a = 1

and from file file2.py, I want to do something like

import file1
print file1.a

without modifying file1.py

4
i bet that if you tell a reason why you need this, we could give you a better way to implement it. - RoeeK
Describing the task at hand could help with a better solution - Jakob Bowyer
It's still nice to know if this is possible, whether or not it's a good idea. - mwcz
phihag answered my questions, but FYI I have a bunch of python files that create a particular object. I am writing a script to compare the outputs. And if your next question is what is the point of the python files, they do create a bunch of output files, but it is a lot easier for me to compare the python object instead of parsing the output files. - Colin

4 Answers

4
votes
import imp
m = imp.find_module('file1')
file1 = imp.load_module('__main__', *m)

That being said, you should really think about modifying file1.py instead of using this hack.

4
votes
from runpy import run_module
data = run_module("file1", run_name="__main__")
print data["a"]

You don't need to mess with the import internals to do things like this any more (and as an added bonus, you will avoid blocking access to your real __main__ module namespace)

3
votes

You can't; that's the purpose of the main sentinel in the first place. If variables defined in the main sentinel are useful outside of it then they should be defined outside of it to begin with.

0
votes

You would need to declare a outside of the if __name__ == '__main__' scope. Right now, it only exists within the scope of that if block.

a = 0
if __name__ == '__main__':
    a = 1