我在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. 更改当前目录
- 4. 如何从python脚本更改当前目录?
- 5. Java Apache FTPClient:如何知道我的当前目录
- 6. 如何知道当前脚本所在的目录
- 7. Shell脚本当前目录?
- 8. 更改父shell的目录
- 9. 在Python中更改调用者的当前工作目录
- 10. 如何知道当前PC
- 11. 检测AVQueuePlayer中的当前项目并知道它何时更改?
- 12. 如何将目录中的内容复制到shell中的当前目录中?
- 13. 更改PHP的当前目录
- 14. 更改FileSystemObject的当前目录
- 15. 如何更改当前目录中的棋子
- 16. Python:是否可以在不更改实际当前目录的情况下更改Windows命令行shell当前目录?
- 17. 在Django中,我如何知道当前登录的用户?
- 18. 如何在python中更改目录youtube_dl
- 19. .net OpenFileDialog更改当前目录
- 20. 如何使os.walk改变当前目录
- 21. 在mac中通过shell脚本知道当前登录的用户的语言
- 22. 如何知道项目的lib目录?
- 23. 如何更改clisp的当前目录一旦启动?
- 24. 将工作目录更改为当前脚本的目录
- 25. 如何将PHP中的目录更改为当前登录的用户路径
- 26. shell如何知道它在哪个目录?
- 27. 在Python中更改目录
- 28. Java程序可以知道它的当前目录吗?
- 29. 从红宝石脚本更改调用shell的当前工作目录
- 30. 如何在C#中更改执行shell的目录?
@Ignacio,你是什么意思? – astay13
这已经在讨论[这里] [1]:http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – mudda
@ astay13 - 我认为Ignacio意味着你不打算改变目录到你的模块路径。您应该检出PYTHONPATH环境变量。 – simon