path to python file given module

G

Gene

Is there a way to get a relative or absolute path to a python file once
it's been imported as a module?

For example, I type:
and I want a string that represents the path to filegen.py (either
relative to current working directory or the absolute path)
 
G

Gene

that method doesn't seem to work as well on UNIX:

wla apocalypse[94] ~/filegen > ls
filegen.py OLDwla_csv2objects.py wlaclasses.py
filegen.pyc templates/ wlaclasses.pyc
gen_all_from_csv.py test.py*
wla apocalypse[95] ~/filegen > python
....None
 
S

Steve Holden

Gene said:
that method doesn't seem to work as well on UNIX:

wla apocalypse[94] ~/filegen > ls
filegen.py OLDwla_csv2objects.py wlaclasses.py
filegen.pyc templates/ wlaclasses.pyc
gen_all_from_csv.py test.py*
wla apocalypse[95] ~/filegen > python
....

Use the module's __file__ attribute:

While this doesn't give you the source, it goves you enough to make a
fair guess about where the source is likely to be, and a littel further
manipulation should be able to confirm that.

regards
Steve
 
K

Kartic

That is because your module in not in a standard location that python
can find it in. It is not that inspect.getsourcefile() is not working.

Actually if you try reloading your filegen module after the os.chdir(),
you will see that import fails. If you copy your filegen directory to
the site-packages directory of python, you will get the complete path
of the module no matter where you are inside your script.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,186
Latest member
vinaykumar_nevatia

Latest Threads

Top