Skip to main content

Python: Running __main__ from Another Script

Let's say you have a script temp.py:
def f(n):
print "n = %s" % n

if __name__ == '__main__':
f(5)
How do you run the __main__ without calling the script on the command line? That is, how do you call it from within another Python script? Simply importing it isn't good enough. Here's how to run the other module's __main__:
>>> import temp
>>> execfile(temp.__file__)
n = 5

Comments

Bobox said…
Beware that with this kind of thing now you have:
>> temp.f != f
True

The temp file is read two times, first as a module, second as a standole file.

This can be tricky if you have this in temp.py:
a = []
def f(x):
a.append(x)
return x
if __name__ == "__main__":
f(5)
now:
>> import temp
>> execfile(temp.__file__)
5
>> temp.a
[]