views:

61

answers:

2

I want to write some python package installing script in Python into virtualenv. I write a function for installing virtualenv

def prepareRadioenv():
    if not os.path.exists('radioenv'):
        print 'Create radioenv'
        system('easy_install virtualenv')
        system('virtualenv --no-site-package radioenv')
    print 'Activate radioenv'
    system('source radioenv/bin/activate')

I try to use "source radioenv/bin/activate" to activate the virtual environment, unfortunately, os.system create a subprocess for doing the command. The environment change made by activate disappear with the subprocess, it doesn't affect the Python process. Here comes the problem, how can I execute some context-aware command sequence in Python?

Another example:

system("cd foo")
system("./bar")

Here the cd doens't affect following system(".bar"). How to make those environment context lives in different commands?

Is there something like context-aware shell? So that I can write some Python code like this:

shell = ShellContext()
shell.system("cd bar")
shell.system("./configure")
shell.system("make install")
if os.path.exists('bar'):
    shell.system("remove")

Thanks.

+2  A: 

To activate the virtualenv from within Python, use the activate_this.py script (which is created with the virtualenv) with execfile.

activate_this = os.path.join("path/to/radioenv", "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))
Daniel Roseman
A: 

You are trying to use Python as a shell?

In parallel with the answer by Daniel Roseman, which seems to be the biggest part of what you need, note that:

shell.system("cd bar")

is spelt in Python as:

os.chdir("bar")

Check the os module for other functions you seem to need, like rmdir, remove and mkdir.

ΤΖΩΤΖΙΟΥ