How to get initial absolute working dir reliably?

K

kj

What's the most reliable way for "module code" to determine the
absolute path of the working directory at the start of execution?

(By "module code" I mean code that lives in a file that is not
meant to be run as a script, but rather it is meant to be loaded
as the result of some import statement. In other words, "module
code" is code that must operate under the assumption that it can
be loaded at any time after the start of execution.)

Functions like os.path.abspath produce wrong results if the working
directory is changed, e.g. through os.chdir, so it is not terribly
reliable for determining the initial working directory.

Basically, I'm looking for a read-only variable (or variables)
initialized by Python at the start of execution, and from which
the initial working directory may be read or computed.


Thanks!
 
A

alex23

What's the most reliable way for "module code" to determine the
absolute path of the working directory at the start of execution?

Here's some very simple code that relies on the singleton nature of modules that might be enough for your needs:

import os

_workingdir = None

def set():
global _workingdir
_workingdir = os.getcwd()

def get():
return _workingdir

At the start of your application, import workingdir and do a workingdir.set(). Then when you need to retrieve it, import it again and use workingdir.get():

a.py:
import workingdir
workingdir.set()

b.py:
import workingdir
print workingdir.get()

test.py:
import a
import b

You could also remove the need to call the .set() by implicitly assigning on the first import:

if '_workingdir' not in locals():
_workingdir = os.getcwd()

But I like the explicitness.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top