简体   繁体   English

当前工作目录在python中不匹配

[英]current working directory mismatch in python

I have imported a existing filesystem folder as the new project folder in eclipse. 我已将现有文件系统文件夹导入为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. 但是,从eclipse和命令行执行时,它给出的值不同。 Location is same in both place. 位置在两个地方都相同。 Please help me resolve this issue. 请帮助我解决此问题。 Operating system is windows here 操作系统在这里是Windows

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 然后使用basedir查找您的文件

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. window-> preferences-> PyDev-> Interpreters-> Python Interpreter TAB(环境)可以通过选择名称为PROJECT_LOC和变量(另一个按钮)的NEW并选择project_loc来指定引用project_loc的PROJECT_LOC。

For some reasons those variables are not visible in python. 由于某些原因,这些变量在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 PROJECT_LOC应该在那了

I have used the sys package instead of os. 我用的是sys软件包而不是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. 我可以从eclipse以及从命令行运行它以获得正确的路径。 Thanks for the help . 谢谢您的帮助 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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