Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make __name__ == '__main__' when running module

Tags:

python

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

like image 464
Colin Avatar asked Mar 20 '26 16:03

Colin


1 Answers

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)

like image 152
ncoghlan Avatar answered Mar 23 '26 05:03

ncoghlan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!