howto obtain directory where current (running) py-file is placed?

sjdevnull at yahoo.com sjdevnull at yahoo.com
Fri Jun 8 09:24:52 CEST 2007


dmitrey wrote:
> Hi all,
> I guess this question was asked many times before, but I don't know
> keywords for web search.
>
> Thank you in advance, D.

In the future, please ask your question in the body of your message
(not just in the subject line).

This question has no answer in general.  There are some things like
__file__ that may be "good enough" depending on your usage, but keep
in mind in general that:
1. __file__ may be altered directly by the program and give an answer
that has no past or current relationship to any filename for the file
that contains the code currently being run.
2. Even if you make no changes, it can contain arbitrary results in
not uncommon situations (e.g. in my local install, an interactive
python session--or one from a here-document in the shell--lists
~/.pythonrc or "<stdin>" in __file__, even though in neither case was
I running my .pythonrc or a file named "<stdin>"
3. Without that, any file may have 0, 1, or many names; those names
may differ now from what they were when the file was first accessed.
So __file__ may refer to an unlinked name (even in the case where at
least one name that existed when you first executed the file is still
valid), or may even e the name of another, different file that was
created (or linked/renamed) after you started running things.

Depending on your needs, those factors may or may not matter.  They're
certainly worth being aware of, and for some applications they may
have massive security implications.




More information about the Python-list mailing list