Import a module from a specific file path

Marko Rauhamaa marko at
Sat Nov 22 07:28:48 CET 2014

Ben Finney <ben+python at>:

> Solutions usually seem to entail contortions of cluttering the import
> block by discovering the current path, and fussing around with
> ‘sys.path’, before finally doing the import::
>     #! /usr/bin/python3
>     import sys
>     import os.path
>     program_dir = os.path.dirname(__file__)

More robustly:

   program_dir = os.path.dirname(os.path.realname(__file__))

Executables are often soft links.

> Importantly, once you've come up with how to do it today in Python: Do
> you really consider that superior to simply specifying a filesystem
> path for a file containing the module?

Your complaint is valid. Many modern programming languages (also java,
guile, elisp etc) suffer from it. Java has alleviated the problem with
jar files.

So why don't C programmers complain about the problem?

First, the #include directive does exactly what you are asking: it
supports relative paths. Secondly, you can build executables statically.


More information about the Python-list mailing list