如何知道/更改 Python shell 中的当前目录? [英] How to know/change current directory in Python shell?

查看:54
本文介绍了如何知道/更改 Python shell 中的当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

您可以使用 os 模块.

<预><代码>>>>导入操作系统>>>os.getcwd()'/家/用户'>>>os.chdir("/tmp/")>>>os.getcwd()'/tmp'

但是如果是关于寻找其他模块:你可以设置一个名为PYTHONPATH的环境变量,在Linux下就像

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

然后,解释器也在这个地方搜索 imported 模块.我猜Windows下的名字应该是一样的,但不知道怎么改.

编辑

在 Windows 下:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(取自 http://docs.python.org/using/windows.html)

编辑 2

... 甚至更好:使用 virtualenvvirtualenv_wrapper,这将允许您创建一个开发环境,您可以在其中添加模块路径(add2virtualenv) 不会污染您的安装或正常"工作环境.

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

I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?

解决方案

You can use the os module.

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

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

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

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

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

这篇关于如何知道/更改 Python shell 中的当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆