Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alternate around directories using subprocess

I want to change the current directory using 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 that this should work like a command line unix

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

$ cd $a
$ ls
$ cd $b
$ ls

But it doesn't happen..

How must I do to change the current dir?

Thanks.

like image 700
JonatasTeixeira Avatar asked May 27 '11 15:05

JonatasTeixeira


1 Answers

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

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

Also, you could take a look at a small module I wrote that completes some missing functionality from Python standard library. Probably this module especially https://github.com/ssbarnea/tendo/blob/master/tendo/tee.py

like image 116
sorin Avatar answered Oct 05 '22 22:10

sorin