简体   繁体   中英

current working directory mismatch in python

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM