[Tutor] What is the easiest way to ensure the current working directory is the same as the directory where the main program is saved?

Cameron Simpson cs at cskk.id.au
Fri Jun 25 23:10:24 EDT 2021


On 25Jun2021 19:01, boB Stepp <robertvstepp at gmail.com> wrote:
>"Practical Programming -- An Introduction to Computer Science Using
>Python 3.6, 3rd ed." states on p. 177:  "...When you run a Python
>program, the current working directory is the directory where that
>program is saved..."  I have established that this is not true.  The
>current working directory of the program depends on from what location
>the program is launched.

Correct.

[...]
>Is there an _easy_ way to have a program start with its current
>working directory in the same directory where its source code resides
>no matter from where the program is launched?  Or must I always use
>the __file__ attribute to determine where the source code resides and
>then change directories from there?

The latter.

But I recommend _not_ changing your working directory. It is a process 
global state which affects everything. When someone invokes your 
programme and supplies a filename on the command line, they usually 
expect that name to be resolved from the working directory where they 
invoked the programme.

If the change directory you need to know where you were if you need to 
work with any caller suppplied relative filenames.

>How do people deal with their
>Python applications that in theory may be installed anywhere in a
>user's file system?  There must be some standard way of dealing with
>this that I am too dense to uncover.

Well, broadly you don't care where the code is. You care about the data 
of the person using your programme, which they'll tell you. (Directly 
with filenames or the like, or also by envionment variables.)

When you do care there are two basic approaches that come to mind:

- use __file__, get its dirname, and access some resources you know are 
  installed beside the source; this is generally awkward - you need 
  control during install, and it is possible to ship python source as a 
  zip file and the __file__ paradigm doesn't work there

- have a config file specifying the location of resources

Maybe you could enumerate some circumstances giving you trouble. See 
what can be done.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list