How to get initial absolute working dir reliably?
alex23
wuwei23 at gmail.com
Sun Aug 19 19:58:40 EDT 2012
On Sunday, 19 August 2012 01:19:59 UTC+10, kj wrote:
> 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.
More information about the Python-list
mailing list