ast*_*y13 204 python windows python-3.x python-3.2
我在Windows 7上使用Python 3.2.当我打开Python shell时,我如何知道当前目录是什么以及如何将其更改为我的模块所在的另一个目录?
wal*_*mat 277
您可以使用该os模块.
>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'
Run Code Online (Sandbox Code Playgroud)
但是,如果它是关于寻找其他模块:你可以设置一个名为的环境变量PYTHONPATH,在Linux下就像
export PYTHONPATH=/path/to/my/library:$PYTHONPATH
Run Code Online (Sandbox Code Playgroud)
然后,解释器也在这个地方搜索imported模块.我想在Windows下名称会相同,但不知道如何更改.
编辑
在Windows下:
set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
Run Code Online (Sandbox Code Playgroud)
(取自http://docs.python.org/using/windows.html)
编辑2
......甚至更好:使用virtualenv和virtualenv_wrapper,这将允许您创建一个开发环境,您可以根据需要添加模块路径(add2virtualenv),而不会污染您的安装或"正常"工作环境.
http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html
sim*_*mon 16
你要
import os
os.getcwd()
os.chdir('..')
Run Code Online (Sandbox Code Playgroud)
sha*_*tap 14
>>> import os
>>> os.system('cd c:\mydir')
Run Code Online (Sandbox Code Playgroud)
实际上,os.system()可以执行windows命令提示符可以执行的任何命令,而不仅仅是更改dir.
更改当前目录不是处理在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.
Run Code Online (Sandbox Code Playgroud)
小智 6
在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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
404333 次 |
| 最近记录: |