paths in modules

Paul Boddie paul at boddie.org.uk
Thu Feb 22 11:28:50 EST 2007


On 22 Feb, 17:13, Brandon Mintern <mint... at cse.ohio-state.edu> wrote:
>
> toplevel_dir
> +-main script
> +-wrapper_dir
>   +-some_wrapper
>   +-utility_dir
>     +-some_external_utility

[...]

> And then in some_wrapper, I would have code like:
>
> import os
>
> def use_external_utility():
>   f = os.popen('utility_dir/some_external_utility')
>   lines = f.readlines()
>   f.close()
>   return lines

And you really want to refer to utility_dir relative to some_wrapper.
What you can try is to split the __file__ attribute of some_wrapper -
it's a standard attribute on imported modules - in order to refer to
the module's parent directory (which should correspond to
wrapper_dir):

parent_dir, filename = os.path.split(__file__)

Then you can join the parent directory to the path of the command:

cmd = os.path.join(parent_dir, "utility_dir", "some_external_utility")

The __file__ attribute of modules is documented here:

http://docs.python.org/ref/types.html#l2h-109

Paul




More information about the Python-list mailing list