我在Windows 7上使用Python 3.2。當我打開Python shell時,如何知道當前目錄是什麼以及如何將其更改爲另一個我的模塊所在的目錄?如何知道/更改Python shell中的當前目錄?
回答
可以使用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
...甚至更好:使用virtualenv
和virtualenv_wrapper
,這將是allo您可以創建一個開發環境,您可以隨意添加模塊路徑(add2virtualenv
),而不會污染您的安裝或「正常」工作環境。
http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html
如果import os
你可以使用os.getcwd
來獲得當前工作目錄,您可以使用os.chdir
更改目錄
你想
import os
os.getcwd()
os.chdir('..')
os.chdir('C:\ Users \ Ajeya \ Documents \') ^ SyntaxError:掃描字符串文字時的EOL – AAI
@Whatever,you need如果您在常規(非原始)Python字符串中使用它們,請將反斜槓加倍。 Python也可以讓你使用正斜槓。因此,無論是'os.chdir('C:/ Users/Ajeya/Documents')',還是'os.chdir('C:\\ Users \\ Ajeya \\ Documents')'或者'os.chdir(r 'C:\用戶\ Ajeya \文件')'。 –
改變當前目錄不是對付在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.
>>> import os
>>> os.system('cd c:\mydir')
事實上,os.system()
可以執行任何命令可以執行Windows命令提示符,而不僅僅是更改目錄。
文件 「
- 1. 如何更改SBCL的當前目錄?
- 2. 如何更改當前工作目錄
- 3. Shell腳本中的當前目錄
- 4. 更改當前目錄
- 5. 如何知道當前目錄樹中是否存在文件
- 6. 如何從python腳本更改當前目錄?
- 7. Java Apache FTPClient:如何知道我的當前目錄
- 8. 如何知道當前腳本所在的目錄
- 9. Shell腳本當前目錄?
- 10. 在shell腳本中,如何用變量安全地更改當前目錄?
- 11. 在Python中更改調用者的當前工作目錄
- 12. 更改父shell的目錄
- 13. 如何知道當前PC
- 14. 檢測AVQueuePlayer中的當前項目並知道它何時更改?
- 15. 如何將目錄中的內容複製到shell中的當前目錄中?
- 16. 如何更改當前目錄中的棋子
- 17. 更改節點的當前目錄
- 18. 更改FileSystemObject的當前目錄
- 19. 更改PHP的當前目錄
- 20. 你應該改變shell腳本中的當前目錄嗎?
- 21. Java Unix Shell更改目錄
- 22. Python:是否可以在不更改實際當前目錄的情況下更改Windows命令行shell當前目錄?
- 23. 在Django中,我如何知道當前登錄的用戶?
- 24. 如何在python中更改目錄youtube_dl
- 25. 如何在Python中更改目錄?
- 26. .net OpenFileDialog更改當前目錄
- 27. 無法更改當前工作目錄
- 28. 爲什麼當前目錄更改
- 29. 如何使os.walk改變當前目錄
- 30. 在mac中通過shell腳本知道當前登錄的用戶的語言
@Ignacio,你是什麼意思? – astay13
這已經在討論[這裏] [1]:http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – mudda
@ astay13 - 我認爲Ignacio意味着你不打算改變目錄到你的模塊路徑。您應該檢出PYTHONPATH環境變量。 – simon