1.

How Do I Find The Current Module Name?

Answer»

A module can find out its own module NAME by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many MODULES that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:
def MAIN():
print 'Running test...'
...
if __name__ == '__main__':
main()
__import__('x.y.z') returns
Try:
__import__('x.y.z').y.z
For more realistic situations, you may have to do SOMETHING like
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:
def main():
print 'Running test...'
...
if __name__ == '__main__':
main()
__import__('x.y.z') returns
Try:
__import__('x.y.z').y.z
For more realistic situations, you may have to do something like
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)



Discussion

No Comment Found