cd是用于更改工作目录的shell命令。

如何更改Python中的当前工作目录?


当前回答

下面是一个上下文管理器更改工作目录的示例。它比其他地方提到的ActiveState版本更简单,但这可以完成任务。

上下文管理器:cd

import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

或者使用ContextManager尝试更简洁的等效方法(如下)。

实例

import subprocess # just to call an arbitrary command e.g. 'ls'

# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back wherever we started.

其他回答

更改脚本进程的当前目录很简单。我认为问题实际上是如何更改调用python脚本的命令窗口的当前目录,这非常困难。Windows中的Bat脚本或Bash shell中的Bash脚本可以使用普通的cd命令执行此操作,因为shell本身就是解释器。在Windows和Linux中,Python都是一个程序,任何程序都不能直接更改其父环境。然而,将一个简单的shell脚本与一个Python脚本相结合来完成大部分困难的工作,可以获得所需的结果。例如,为了制作一个带有向后/向前/选择重新访问遍历历史的扩展cd命令,我编写了一个由简单的bat脚本调用的相对复杂的Python脚本。遍历列表存储在文件中,目标目录位于第一行。当python脚本返回时,bat脚本读取文件的第一行,并将其作为cd的参数

if _%1 == _. goto cdDone
if _%1 == _? goto help
if /i _%1 NEQ _-H goto doCd
:help
echo d.bat and dSup.py 2016.03.05. Extended chdir.
echo -C = clear traversal list.
echo -B or nothing = backward (to previous dir).
echo -F or - = forward (to next dir).
echo -R = remove current from list and return to previous.
echo -S = select from list.
echo -H, -h, ? = help.
echo . = make window title current directory.
echo Anything else = target directory.
goto done

:doCd
%~dp0dSup.py %1
for /F %%d in ( %~dp0dSupList ) do (
    cd %%d
    if errorlevel 1 ( %~dp0dSup.py -R )
    goto cdDone
)
:cdDone
title %CD%
:done

python脚本dSup.py是:

import sys, os, msvcrt

def indexNoCase ( slist, s ) :
    for idx in range( len( slist )) :
        if slist[idx].upper() == s.upper() :
            return idx
    raise ValueError

# .........main process ...................
if len( sys.argv ) < 2 :
    cmd = 1 # No argument defaults to -B, the most common operation
elif sys.argv[1][0] == '-':
    if len(sys.argv[1]) == 1 :
        cmd = 2 # '-' alone defaults to -F, second most common operation.
    else :
        cmd = 'CBFRS'.find( sys.argv[1][1:2].upper())
else :
    cmd = -1
    dir = os.path.abspath( sys.argv[1] ) + '\n'

# cmd is -1 = path, 0 = C, 1 = B, 2 = F, 3 = R, 4 = S

fo = open( os.path.dirname( sys.argv[0] ) + '\\dSupList', mode = 'a+t' )
fo.seek( 0 )
dlist = fo.readlines( -1 )
if len( dlist ) == 0 :
    dlist.append( os.getcwd() + '\n' ) # Prime new directory list with current.

if cmd == 1 : # B: move backward, i.e. to previous
    target = dlist.pop(0)
    dlist.append( target )
elif cmd == 2 : # F: move forward, i.e. to next
    target = dlist.pop( len( dlist ) - 1 )
    dlist.insert( 0, target )
elif cmd == 3 : # R: remove current from list. This forces cd to previous, a
                # desireable side-effect
    dlist.pop( 0 )
elif cmd == 4 : # S: select from list
# The current directory (dlist[0]) is included essentially as ESC.
    for idx in range( len( dlist )) :
        print( '(' + str( idx ) + ')', dlist[ idx ][:-1])
    while True :
        inp = msvcrt.getche()
        if inp.isdigit() :
            inp = int( inp )
            if inp < len( dlist ) :
                print( '' ) # Print the newline we didn't get from getche.
                break
        print( ' is out of range' )
# Select 0 means the current directory and the list is not changed. Otherwise
# the selected directory is moved to the top of the list. This can be done by
# either rotating the whole list until the selection is at the head or pop it
# and insert it to 0. It isn't obvious which would be better for the user but
# since pop-insert is simpler, it is used.
    if inp > 0 :
        dlist.insert( 0, dlist.pop( inp ))

elif cmd == -1 : # -1: dir is the requested new directory.
# If it is already in the list then remove it before inserting it at the head.
# This takes care of both the common case of it having been recently visited
# and the less common case of user mistakenly requesting current, in which
# case it is already at the head. Deleting and putting it back is a trivial
# inefficiency.
    try:
        dlist.pop( indexNoCase( dlist, dir ))
    except ValueError :
        pass
    dlist = dlist[:9] # Control list length by removing older dirs (should be
                      # no more than one).
    dlist.insert( 0, dir ) 

fo.truncate( 0 )
if cmd != 0 : # C: clear the list
    fo.writelines( dlist )

fo.close()
exit(0)

您可以通过以下方式更改工作目录:

import os

os.chdir(path)

使用此方法时,需要遵循两个最佳实践:

捕获无效路径上的异常(WindowsError、OSError)。如果抛出异常,请不要执行任何递归操作,尤其是破坏性操作。他们将在旧的道路上运行,而不是在新的道路上。完成后返回到旧目录。这可以通过将chdir调用包装在上下文管理器中以异常安全的方式完成,就像BrianM.Hunt在回答中所做的那样。

在子流程中更改当前工作目录不会更改父流程中的当前工作目录。Python解释器也是如此。不能使用os.chdir()更改调用进程的CWD。

os.chdir()是正确的方法。

下面是一个上下文管理器更改工作目录的示例。它比其他地方提到的ActiveState版本更简单,但这可以完成任务。

上下文管理器:cd

import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

或者使用ContextManager尝试更简洁的等效方法(如下)。

实例

import subprocess # just to call an arbitrary command e.g. 'ls'

# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back wherever we started.

我会这样使用os.chdir:

os.chdir("/path/to/change/to")

顺便说一句,如果需要计算当前路径,请使用os.getcwd()。

更多信息请点击此处