DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Change CWD in Python


The following script demonstrate that in Python, "os.chdir()" will change CWD globally, while run shell "cd" command with subprocess module is a "local" action. If you run "cd dst;touch aaa", the file "aaa" will be created under folder dst, but after this sentence, the CWD won't remian in aaa.

$ cat chdirtest.py
import subprocess, os

def runsh(cmd):
    return subprocess.check_output(cmd, shell=True)

def svn_checkout(src, dst, keepfolder=True):
    print('in svn_checkout before: ' + os.getcwd())
    print('in svn_checkout shell before: ' + runsh('pwd'))
    os.makedirs(dst)
    #os.chdir(dst)
    print('run cd and pwd: ' + runsh('cd ' + dst + ';pwd'))
    print('in svn_checkout after: ' + os.getcwd())
    print('in svn_checkout shell after: ' + runsh('pwd'))

def download():
    print('in download before: ' + os.getcwd())
    print('in download shell before: ' + runsh('pwd'))
    src = '7-Tools/deployment'
    svn_checkout(src, CODE_FOLDER)
    print('in download after: ' + os.getcwd())
    print('in download shell after: ' + runsh('pwd'))

if __name__ == '__main__':
    FOLDER_NAME = 'test'
    if not os.path.exists(FOLDER_NAME):
        os.makedirs(FOLDER_NAME)
    print('in main before: ' + os.getcwd())
    print('in main shell before: ' + runsh('pwd'))
    os.chdir(FOLDER_NAME)
    print('in main after: ' + os.getcwd())
    print('in main shell after: ' + runsh('pwd'))
    PKG_FOLDER = 'packages'
    CODE_FOLDER = 'codes'
    download()

$ python chdirtest.py
in main before: /home/chad/docs/gcp-deploy
in main shell before: /home/chad/docs/gcp-deploy

in main after: /home/chad/docs/gcp-deploy/test
in main shell after: /home/chad/docs/gcp-deploy/test

in download before: /home/chad/docs/gcp-deploy/test
in download shell before: /home/chad/docs/gcp-deploy/test

in svn_checkout before: /home/chad/docs/gcp-deploy/test
in svn_checkout shell before: /home/chad/docs/gcp-deploy/test

run cd and pwd: /home/chad/docs/gcp-deploy/test/codes

in svn_checkout after: /home/chad/docs/gcp-deploy/test
in svn_checkout shell after: /home/chad/docs/gcp-deploy/test

in download after: /home/chad/docs/gcp-deploy/test
in download shell after: /home/chad/docs/gcp-deploy/test


Published

Feb 24, 2014

Last Updated

Feb 24, 2014

Category

Tech

Tags

  • Directory 4
  • Python 136

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor