[Tutor] What is the best way for a program suite to know where it is installed?

Mats Wichmann mats at wichmann.us
Mon Oct 22 10:46:16 EDT 2018


On 10/20/18 9:00 PM, boB Stepp wrote:
> I was just re-reading the entire thread at
>     https://www.mail-archive.com/tutor@python.org/msg77864.html
> And I have asked similar questions previous to that thread.  I still
> do not have a satisfactory answer for the subject line's question that
> both makes sense to me and seems to be good programming practice.  And
> that works for any OS that the program suite is installed under.
> 
> A constantly recurring situation I am having is a programming project
> with a nested directory structure.  Usually I will have "tests" and
> "data" folders nested under the top level project folder.  There may
> be others as well depending on the complexity of the project I am
> attempting.  As far as I can tell, I cannot make any assumptions about
> what the current working directory is when a user starts the program.
> So how can one of my programs *know* what the absolute path is to,
> say, the top level of the program suite?  If I could always reliably
> determine this by my program's code, every other location could be
> determined from the known nested structure of the program suite.  [But
> I have a dim recollection that either Ben or Cameron thought relying
> on the "known nested structure" is brittle at best.]
> 
> So far the best method I've come up with is to make use of "__file__"
> for the initiating program file.  But from past discussions I am not
> certain this is the *best* way.  Is the *best* way going to get me
> into best techniques for installing and distributing programs?  If so,
> this strikes me as a huge mess to dive into!
> 
> TIA!
> 

As you've concluded by now, this isn't a completely trivial exercise,
and you'll possibly get asked the question "why do you think you need to
know that?".

Probably though this is considered one of the more reliable ways:

import os

if __name__ == '__main__':
    script_path = os.path.dirname(os.path.realpath(__file__))
    print("Main module at", script_path)






More information about the Tutor mailing list