2011-11-23 45 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