繁体   English   中英

如何知道/更改 Python shell 中的当前目录?

[英]How to know/change current directory in Python shell?

我在 Windows 7 上使用 Python 3.2。当我打开 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

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

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

你要

import os
os.getcwd()
os.chdir('..')
>>> import os
>>> os.system('cd c:\mydir')

其实os.system()可以执行windows命令提示符可以执行的任何命令,而不仅仅是改变dir。

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

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

更改当前目录不是处理 Python 中查找模块的方法。

相反,请参阅模块搜索路径的文档,了解 Python 如何找到要导入的模块。

这是 标准模块部分的相关内容:

变量 sys.path 是一个字符串列表,用于确定解释器的模块搜索路径。 它被初始化为从环境变量 PYTHONPATH 中获取的默认路径,如果未设置 PYTHONPATH,则从内置默认值中初始化。 您可以使用标准列表操作修改它:

>>> 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.getcwd获取当前工作目录,也可以使用os.chdir更改目录

你可以试试这个:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM