python - is it possible to change working directory when executing a .py file in different folder? -


for example,here directory tree:

+--- test.py | +--- [subdir]       |       +--- another.py 

test.py:

import os os.system('python subdir/another.py') 

another.py:

import os os.mkdir('whatever') 

after running test.py ,i expected have folder whatever in subdir,but got is:

+--- test.py | +--- [subdir] |     | |     +--- another.py | +--- whatever 

the reason quite obvious:working directory hadn't been changed subdir.so possible change working directory when executing .py file in different folder? note:

  1. any function allowed, os.system example
  2. os.system('cd xxx') , os.chdir not allowed

edit: decide use context manager,following answer in
https://stackoverflow.com/posts/17589236/edit

import os import subprocess # call arbitrary command e.g. 'ls'  class cd:     def __init__(self, newpath):         self.newpath = newpath      def __enter__(self):         self.savedpath = os.getcwd()         os.chdir(self.newpath)      def __exit__(self, etype, value, traceback):         os.chdir(self.savedpath)  # can enter directory this: cd("~/library"):    # in ~/library    subprocess.call("ls")  # outside context manager started. 

ummm, function so: os.chdir(path).

maybe it's little bit confusing or incosistent because function obtain current working directory called os.getcwd() , has no counterpart setter. nevertheless, doc says chdir changes cwd.

in python 3.x path can valid file descriptor, while in 2.x branch fchdir(fd) must used.


Comments

Popular posts from this blog

c# - SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList -

how can i manage url using .htaccess in php? -

ios - I get the error Property '...' not found on object of type '...' -