How to alternate directories using a subprocess

I want to change the current directory using a subprocess.

For example:

import os, sys, subprocess os.environ['a'] = '/home' os.environ['b'] = '/' subprocess.call('cd $a', shell=True) subprocess.call('ls', shell=True) subprocess.call('cd $b', shell=True) subprocess.call('ls', shell=True) 

I think this should work as a unix command line

 $ export a='/home' $ export b='/' $ cd $a $ ls $ cd $b $ ls 

But this does not happen.

How do I do to change the current directory?

Thanks.

+8
python unix subprocess
source share
1 answer

To change the directory, use os.chdir() instead.

You can also execute commands in specific directoeies by running subprocess.Popen(...) - it has the optional parameter cwd=None . Just use it to specify the working directory.

Alternatively, you can take a look at the small module I wrote that completes some of the missing functions from the Python standard library. Probably this module is especially https://github.com/ssbarnea/tendo/blob/master/tendo/tee.py

+13
source share

All Articles