current working directory mismatch in python

2.3k views Asked by At

I have imported a existing filesystem folder as the new project folder in eclipse. I have a script which get the current working directory path of the code. I need to change directory location to acccess files in other directory related to it. But It is giving different value when executed from eclipse and from the command line. Location is same in both place. Please help me resolve this issue. Operating system is windows here

import os
print os.getcwd()
os.chdir(os.path.dirname(os.getcwd()))
print os.getcwd()

One result is this

C:\Automation\trunk\Base\TestScripts
C:\Automation\trunk\Base

Other result is this

C:\Automation\trunk\UsefulScripts
C:\Automation\trunk

Second result is the one I expect, and that is where the code is located exactly.

2

There are 2 answers

3
Saranya Sridharan On

I have used the sys package instead of os. It works as expected.

import os,sys
currentpath = sys.path[0]
print currentpath

I can able to run it from eclipse and also from command line to get the correct path. Thanks for the help .

10
mbieren On

watch out you cannot rely on that. Do the following :

basedir = os.environ.get('PROJECT_LOC', None)

if not basedir:
     basedir = sys.path[0]    # We are on commandline. sys.path OK

Then use basedir to find your files

Update

you have to specify this variable in the runtime of the interpreter

window->preferences->PyDev->Interpreters->Python Interpreter TAB (environment) There you can specify PROJECT_LOC referring to project_loc by selecting NEW with name PROJECT_LOC and variable (the other button) and selecting project_loc.

For some reasons those variables are not visible in python.

You can check this now with

def read_all_variables():
    for key in os.environ.keys():
        print ("%30s %s" % (key,os.environ[key]))

PROJECT_LOC should be there now