How do I change directory back to my original working directory with Python?

前端 未结 6 823
梦谈多话
梦谈多话 2020-12-15 04:07

I have a function that resembles the one below. I\'m not sure how to use the os module to get back to my original working directory at the conclusion of the jar\'s execution

6条回答
  •  死守一世寂寞
    2020-12-15 04:44

    The advice to use os.chdir(owd) is good. It would be wise to put the code which needs the changed directory in a try:finally block (or in python 2.6 and later, a with: block.) That reduces the risk that you will accidentally put a return in the code before the change back to the original directory.

    def run(): 
        owd = os.getcwd()
        try:
            #first change dir to build_dir path
            os.chdir(testDir)
            #run jar from test directory
            os.system(cmd)
        finally:
            #change dir back to original working directory (owd)
            os.chdir(owd)
    

提交回复
热议问题