Tuesday, January 23, 2007

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__':
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

1 comment:

Bobox said...

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

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):
return x
if __name__ == "__main__":
>> import temp
>> execfile(temp.__file__)
>> temp.a