Mic*_*bbé 717
您可以使用以下命令更改工作目录:
import os
os.chdir(path)
Run Code Online (Sandbox Code Playgroud)
使用此方法时,有两个最佳做法:
更改子进程中的当前工作目录不会更改父进程中的当前工作目录.对于Python解释器也是如此.您无法使用os.chdir()更改调用进程的CWD.
Bri*_*unt 296
以下是更改工作目录的上下文管理器示例.它比其他地方引用的ActiveState版本更简单,但这可以完成工作.
cdimport 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)
Run Code Online (Sandbox Code Playgroud)
或者使用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.
Run Code Online (Sandbox Code Playgroud)
Eva*_*ark 136
我会用os.chdir这样的:
os.chdir("/path/to/change/to")
Run Code Online (Sandbox Code Playgroud)
顺便说一下,如果你需要弄清楚你当前的路径,请使用os.getcwd().
更多这里
cdu*_*001 107
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)
Run Code Online (Sandbox Code Playgroud)
然后,即使抛出异常,该目录也会被还原:
os.chdir('/home')
with cd('/tmp'):
# ...
raise Exception("There's no place like home.")
# Directory is now back to '/home'.
Run Code Online (Sandbox Code Playgroud)
Bri*_*per 23
如果您使用的Python的一个相对较新的版本,你也可以使用一个上下文管理器,比如这一个:
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
Run Code Online (Sandbox Code Playgroud)
UPDATE
如果你喜欢自己动手:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
Run Code Online (Sandbox Code Playgroud)
mrd*_*ave 13
正如其他人已经指出的那样,上述所有解决方案只会改变当前进程的工作目录.当您退回到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")
Run Code Online (Sandbox Code Playgroud)
import os
abs_path = 'C://a/b/c'
rel_path = './folder'
os.chdir(abs_path)
os.chdir(rel_path)
Run Code Online (Sandbox Code Playgroud)
您可以同时使用 os.chdir(abs_path) 或 os.chdir(rel_path),无需调用 os.getcwd() 即可使用相对路径。
进一步指向Brian指出的方向并基于sh(1.0.8+)
from sh import cd, ls
cd('/tmp')
print ls()
Run Code Online (Sandbox Code Playgroud)