cd
कार्य निर्देशिका को बदलने के लिए शेल कमांड है।
मैं पायथन में वर्तमान कार्य निर्देशिका को कैसे बदलूं?
os.getcwd()
cd
कार्य निर्देशिका को बदलने के लिए शेल कमांड है।
मैं पायथन में वर्तमान कार्य निर्देशिका को कैसे बदलूं?
os.getcwd()
जवाबों:
आप इसके साथ कार्य निर्देशिका बदल सकते हैं:
import os
os.chdir(path)
इस पद्धति का उपयोग करते समय दो सर्वोत्तम अभ्यास हैं:
वर्तमान वर्किंग डायरेक्टरी को सबप्रोसेस में बदलने से पेरेंट प्रोसेस में करंट वर्किंग डायरेक्टरी नहीं बदलती है। यह पायथन दुभाषिया के रूप में अच्छी तरह से सच है। आप os.chdir()
कॉलिंग प्रक्रिया के CWD को बदलने के लिए उपयोग नहीं कर सकते ।
os.chdir()
, जब तक आपको नहीं लगता कि आप जानते हैं कि आप क्या कर रहे हैं। ( आप शायद नहीं हैं। )
os.chdir("C:/path/to/location")
कार्य निर्देशिका को बदलने के लिए एक संदर्भ प्रबंधक का एक उदाहरण यहां दिया गया है। यह 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.
return self
के अंत में जोड़ सकते हैं __enter__
। इस तरह आप कर सकते हैं with cd('foo') as cm:
और पिछले dir तक पहुँच सकते हैंcm.savedPath
मैं 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'.
try/finally
)।
yield
और क्या नहीं return
? क्या यह एक जनरेटर माना जाता है?
यदि आप पायथन के अपेक्षाकृत नए संस्करण का उपयोग कर रहे हैं, तो आप एक संदर्भ प्रबंधक का उपयोग भी कर सकते हैं, जैसे कि यह :
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)
contextlib.contextmanager
डेकोरेटर अच्छा है। देखें cdunn2001 के डेकोरेटर आधारित जवाब है, जो आदर्श अब स्वीकार किए जाते हैं जवाब होगा।
जैसा कि पहले ही दूसरों ने बताया है, उपरोक्त सभी समाधान केवल वर्तमान प्रक्रिया की कार्यशील निर्देशिका को बदलते हैं। यह तब खो जाता है जब आप यूनिक्स शेल से वापस बाहर निकलते हैं। अगर आप इस भयानक हैक के साथ यूनिक्स पर मूल शैल निर्देशिका को बदल सकते हैं:
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()
सही तरीका है।
import os
abs_path = 'C://a/b/c'
rel_path = './folder'
os.chdir(abs_path)
os.chdir(rel_path)
आप os.chdir (abs_path) या os.chdir (rel_path) के साथ दोनों का उपयोग कर सकते हैं, रिश्तेदार पथ का उपयोग करने के लिए os.getcwd () को कॉल करने की कोई आवश्यकता नहीं है।
ब्रायन द्वारा बताई गई दिशा और श पर आधारित (1.0.8+)
from sh import cd, ls
cd('/tmp')
print ls()
यदि आप स्पाइडर और प्यार GUI का उपयोग करते हैं, तो आप बस अपनी स्क्रीन के ऊपरी दाएं कोने पर फ़ोल्डर बटन पर क्लिक कर सकते हैं और वर्तमान निर्देशिका के रूप में इच्छित फ़ोल्डर / निर्देशिकाओं के माध्यम से नेविगेट कर सकते हैं। ऐसा करने के बाद आप स्पाइडर आईडीई में विंडो के फाइल एक्सप्लोरर टैब पर जा सकते हैं और वहां मौजूद सभी फाइलों / फ़ोल्डरों को देख सकते हैं। अपने वर्तमान कार्य निर्देशिका की जाँच करने के लिए स्पाइडर आईडीई के कंसोल पर जाएं और बस टाइप करें
pwd
यह उसी रास्ते को प्रिंट करेगा जैसा आपने पहले चुना है।
स्क्रिप्ट प्रक्रिया की वर्तमान निर्देशिका को बदलना तुच्छ है। मुझे लगता है कि प्रश्न वास्तव में कमांड विंडो की वर्तमान निर्देशिका को कैसे बदलना है जिसमें से एक पायथन स्क्रिप्ट को लागू किया जाता है, जो बहुत मुश्किल है। विंडोज में एक बैट स्क्रिप्ट या बैश शेल में एक बैश स्क्रिप्ट एक साधारण सीडी कमांड के साथ ऐसा कर सकती है क्योंकि शेल खुद इंटरप्रेटर है। विंडोज और लिनक्स दोनों में पायथन एक कार्यक्रम है और कोई भी कार्यक्रम सीधे अपने माता-पिता के वातावरण को नहीं बदल सकता है। हालाँकि, एक साधारण शेल स्क्रिप्ट का संयोजन पाइथन स्क्रिप्ट के साथ किया जाता है, जिसमें अधिकांश हार्ड सामग्री वांछित परिणाम प्राप्त कर सकती है। उदाहरण के लिए, पिछड़े / आगे / चयन के लिए ट्रैवर्सल इतिहास के साथ एक विस्तारित सीडी कमांड बनाने के लिए, मैंने एक साधारण बैट स्क्रिप्ट द्वारा लिखी गई अपेक्षाकृत जटिल पायथन स्क्रिप्ट लिखी। त्रैमासिक सूची एक फ़ाइल में संग्रहीत है, पहली पंक्ति पर लक्ष्य निर्देशिका के साथ। जब पाइथन स्क्रिप्ट वापस आती है, तो बैट स्क्रिप्ट फ़ाइल की पहली पंक्ति पढ़ती है और इसे 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)
os.chdir(os.path.join(os.path.abspath(os.path.curdir),u'subfolder'))
- या?