2011-11-23 152 views
132

我在Windows 7上使用Python 3.2。当我打开Python shell时,如何知道当前目录是什么以及如何将其更改为另一个我的模块所在的目录?如何知道/更改Python shell中的当前目录?

+1

@Ignacio,你是什么意思? – astay13

+0

这已经在讨论[这里] [1]:http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – mudda

+4

@ astay13 - 我认为Ignacio意味着你不打算改变目录到你的模块路径。您应该检出PYTHONPATH环境变量。 – simon

回答

188

可以使用os模块。

>>> import os 
>>> os.getcwd() 
'/home/user' 
>>> os.chdir("/tmp/") 
>>> os.getcwd() 
'/tmp' 

但如果它是关于寻找其他模块:可以设置称为PYTHONPATH的环境变量,在Linux下会像

export PYTHONPATH=/path/to/my/library:$PYTHONPATH 

然后,解释搜索也是在这个地方import版模块。我猜这个名字在Windows下是一样的,但不知道如何改变。

编辑

在Windows下:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib 

(从http://docs.python.org/using/windows.html拍摄)

编辑2

...甚至更好:使用virtualenvvirtualenv_wrapper,这将是allo您可以创建一个开发环境,您可以随意添加模块路径(add2virtualenv),而不会污染您的安装或“正常”工作环境。

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

+0

你是正确的编辑你的问题,添加有关'PYTHONPATH'的建议,但请注意,OP指定Windows ... – simon

+0

在Windows下PYTHONPATH有什么问题?但我确定了我的答案。 –

+0

我是否必须在Windows命令行或Python shell中设置PYTHONPATH? – astay13

4

如果import os你可以使用os.getcwd来获得当前工作目录,您可以使用os.chdir更改目录

12

你想

import os 
os.getcwd() 
os.chdir('..') 
+1

os.chdir('C:\ Users \ Ajeya \ Documents \') ^ SyntaxError:扫描字符串文字时的EOL – AAI

+1

@Whatever,you need如果您在常规(非原始)Python字符串中使用它们,请将反斜杠加倍。 Python也可以让你使用正斜杠。因此,无论是'os.chdir('C:/ Users/Ajeya/Documents')',还是'os.chdir('C:\\ Users \\ Ajeya \\ Documents')'或者'os.chdir(r 'C:\用户\ Ajeya \文件')'。 –

4

改变当前目录不是对付在Python找到模块的方式。

相反,请参阅文档The Module Search Path了解Python如何找到要导入的模块。

这里是Standard Modules部分中的相关位:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

在回答有关获取和设置当前目录原题:

>>> help(os.getcwd) 

getcwd(...) 
    getcwd() -> path 

    Return a string representing the current working directory. 

>>> help(os.chdir) 

chdir(...) 
    chdir(path) 

    Change the current working directory to the specified path. 
7
>>> import os 
>>> os.system('cd c:\mydir') 

事实上,os.system()可以执行任何命令可以执行Windows命令提示符,而不仅仅是更改目录。

+0

文件 “”,1个线 使用os.system( 'CD C:\用户\ Ajeya \文档\') ^ 语法错误:EOL同时扫描字符串字面 – AAI

0

在python中改变当前工作目录的最简单方法是使用'os'包。下面是一个Windows计算机的例子:

#import the os package 
import os 
# Confirm the current working directory 
os.getcwd() 
# use '\\' while chaning the directory 
os.chdir("C:\\user\\foldername") 
+0

这是如何从接受的答案有什么不同? – Iceman

+0

使用“\\”和关于Windows计算机的说明。但我同意接受的答案更具描述性。 – sambeet