[Tutor] Can anyone explain this

Marc Tompkins marc.tompkins at gmail.com
Thu Aug 8 04:19:39 CEST 2013


On Fri, Aug 2, 2013 at 4:33 PM, Amandeep Behl <amandeep.qa at gmail.com> wrote:

> Can anyone explain this code below:
>
>

> import sys
> import os
>
> if __name__ == '__main__':
>     sys.path.insert(0, "..")
> else:
>     sys.path.insert(0, os.path.join(
>         os.path.split(__file__)[0], '..'))
>


When you run this module as a standalone, the value of __name__ will be
"__main__"; this is a standard test to see whether you're running it from
the command line or importing it from another script.

If you're running this code standalone, it will insert the directory one
level up from the current working directory (..) as the first item in the
Python path, so that subsequent imports will look there first.

If you're calling this code from another script, it can't rely on knowing
the current working directory - so it calls os.path.split to find the
directory where this file is located; then it inserts the parent of that
directory as the first item in the Python path.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130807/cc63b826/attachment-0001.html>


More information about the Tutor mailing list