[python] 파이썬에서 작업 디렉토리를 어떻게 변경합니까?

cd 작업 디렉토리를 변경하는 쉘 명령입니다.

파이썬에서 현재 작업 디렉토리를 어떻게 변경합니까?



답변

다음을 사용하여 작업 디렉토리를 변경할 수 있습니다.

import os

os.chdir(path)

이 방법을 사용할 때 따라야 할 두 가지 모범 사례가 있습니다.

  1. 잘못된 경로에서 예외 (WindowsError, OSError)를 포착하십시오. 예외가 발생하면 재귀 작업, 특히 파괴적인 작업을 수행하지 마십시오. 그들은 새로운 경로가 아닌 오래된 경로에서 작동합니다.
  2. 완료되면 이전 디렉토리로 돌아갑니다. 이것은 Brian M. Hunt가 그의 답변 에서했던 것처럼 컨텍스트 관리자에 chdir 호출을 래핑하여 예외 안전 방식으로 수행 할 수 있습니다 .

서브 프로세스에서 현재 작업 디렉토리를 변경해도 상위 프로세스의 현재 작업 디렉토리는 변경되지 않습니다. 이것은 파이썬 인터프리터에서도 마찬가지입니다. os.chdir()호출 프로세스의 CWD를 변경하는 데 사용할 수 없습니다 .


답변

다음은 작업 디렉토리를 변경하는 컨텍스트 관리자의 예입니다. 다른 곳에서 참조 되는 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().

여기


답변

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'.


답변

파이썬의 비교적 새로운 버전을 사용하는 경우, 당신은 또한 같은 맥락 관리자를 사용할 수 있습니다 이 하나 :

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

최신 정보

자신의 롤을 선호하는 경우 :

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 쉘로 돌아갈 때 손실됩니다. 필사적 인 경우이 끔찍한 핵으로 Unix의 상위 쉘 디렉토리를 변경할 있습니다.

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")


답변

os.chdir() 올바른 방법입니다.