셸 명령에서와 같이 cd
를 입력하여 작업 디렉터리를 변경합니다.
Python에서 현재 작업 디렉터리를 변경하려면 어떻게 하나요?
작업 디렉터리는 다음으로 변경할 수 있습니다:
import os
os.chdir(path)
이 방법을 사용할 때 따라야 할 두 가지 모범 사례가 있습니다:
하위 프로세스에서 현재 작업 디렉터리를 변경해도 부모 프로세스의 현재 작업 디렉터리는 변경되지 않습니다. 이것은 파이썬 인터프리터에서도 마찬가지입니다. 호출 프로세스의 CWD를 변경하기 위해 os.chdir()
을 사용할 수 없습니다.
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)
[더 간결하게 fte (아래)] 또는 다음 (https://stackoverflow.com/a/24176022/263998) 을 [콘테스트만거] (https://docs.python.org/2/library/contextlib.html # 콘테스트리발콘테스트만거).
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("/path/to/change/to")
그나저나 사용할 경우 현재 경로 () ',' 로지제스우드 파악해야 합니다.
더 here
'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
[1]: # working_directory http://software.clapper.org/grizzled-python/epydoc/grizzled.os-module.html
원할 경우 자신의 선보일 예정이다.
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
위에서 지적한 것처럼, 이미 다른 사람이 모든 솔루션을 디렉토리에만 apc® 변경하십시오 디렉터리이고 현재 프로세스. 이는 종료하십시오 백됩니다 손실됩니다 bsbab-unix 쉘입니다. 변경하십시오 절박한 경우 상위 쉘로 bsbab-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")
현재 디렉터리이고 스크립트입니다 변화하는 과정은 아주. 내 생각엔 문제는 실제로 어떻게 변경합니까 있는 창이 파이썬 스크립트가 현재 디렉터리이고 명령을 한 호출되었을, 이는 매우 어렵다. Windows 에서 스크립트를 Bash 스크립트입니다 배트 또는 cd 명령을 할 수 있는 평범한 배시 셸을 통해 이 때문에 쉘로 자체가 통역을 했다고 한다. 이 두 가지 않고 변경할 수 있는 프로그램은 Windows, Linux 파이썬 환경을 직접 parent& # 39 의 프로그램이다. 그러나 파이썬 스크립트를 간단한 shell script 와 함께 하는 대부분의 하드 그런거 원하는 결과를 얻을 수 있습니다. 예를 들어, 역사에 대한 문제를 뒤로 / cd 를 만들기 위해 ehas 명령과 함께 순회, 내가 앞으로 / 파이썬 스크립트를 통해 비교적 복잡한 작성했습니까 호출되었을 간단한 배트 스크립트입니다. 이 목록은 저장됩니까 파일을 대상으로 첫 번째 순회 디렉토에 할말이다 파이썬 스크립트를 때, 첫 번째 줄은 판독합니다 스크립트입니다 되돌려줍니다 방망이 때문에 파일 및 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
파이썬 스크립트, 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)