cd
和shell命令中一样,改变工作目录。
如何在 Python 中改变当前工作目录?
你可以用以下方法改变工作目录。
import os
os.chdir(path)
使用该方法时,有两个最佳实践需要遵循。
1.捕捉无效路径的异常(WindowsError, OSError)。 如果异常被抛出,不要进行任何递归操作,特别是破坏性的操作。 他们会在旧的路径上操作,而不是新的路径。 2.2.完成后返回到你的旧目录。 这可以通过将你的chdir调用包装在一个上下文管理器中,以异常安全的方式完成,就像Brian M. Hunt在他的答案中做的那样。
改变子进程中的当前工作目录并不改变父进程中的当前工作目录。 这在 Python 解释器中也是如此。 你不能使用os.chdir()
来改变调用进程的 CWD。
这里有一个改变工作目录的上下文管理器的例子,它比其他地方提到的[ActiveState版本]()更简单,但它能完成工作。 它比其他地方提到的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()
。
更多[这里][1]
cd()
使用一个生成器和一个装饰器很容易编写。
from contextlib import contextmanager
import os
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
然后,即使在抛出异常后,目录也会被还原。
os.chdir('/home')
with cd('/tmp'):
# ...
raise Exception("There's no place like home.")
# Directory is now back to '/home'.
如果你使用的是比较新的Python版本,你也可以使用上下文管理器,比如[这个][1]。
from __future__ import with_statement
from grizzled.os import working_directory
with working_directory(path_to_directory):
# code in here occurs within the directory
# code here is in the original directory
[1]: http://software.clapper.org/grizzled-python/epydoc/grizzled.os-module.html#working_directory
更新
如果你喜欢自己卷。
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
正如其他人已经指出的那样,以上所有的解决方案只是改变了当前进程的工作目录。 当你退出回到Unix shell时,这个目录就会丢失。 如果绝望的话,你可以用这个可怕的黑客方法**改变Unix上的父shell目录。
def quote_against_shell_expansion(s):
import pipes
return pipes.quote(s)
def put_text_back_into_terminal_input_buffer(text):
# use of this means that it only works in an interactive session
# (and if the user types while it runs they could insert characters between the characters in 'text'!)
import fcntl, termios
for c in text:
fcntl.ioctl(1, termios.TIOCSTI, c)
def change_parent_process_directory(dest):
# the horror
put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")
改变脚本进程的当前目录是很琐碎的。 我认为问题其实是如何改变命令窗口的当前目录,从命令窗口中调用python脚本,这是非常困难的。 Windows中的Bat脚本或者Bash shell中的Bash脚本可以通过普通的cd命令来实现,因为shell本身就是解释器。 在Windows和Linux中,Python都是一个程序,没有一个程序可以直接改变它的父程序'的环境。 然而将一个简单的shell脚本和一个Python脚本结合起来,做大部分的难事,可以达到预期的效果。 例如,为了制作一个扩展的cd命令,并带有用于后退/前进/选择重访的遍历历史,我写了一个相对复杂的Python脚本,由一个简单的bat脚本调用。 遍历列表存储在一个文件中,目标目录在第一行。 当python脚本返回时,bat脚本读取文件的第一行并将其作为cd的参数。 完整的bat脚本(为简洁起见,去掉注释)是:{{{5479420}}。
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)