trouselife
trouselife

Reputation: 969

Can I use a single python script to create a virtualenv and install requirements.txt?

I am trying to create a script where i create a virtualenv if it has not been made, and then install requirements.txt in it.

I can't call the normal source /env/bin/activate and activate it, then use pip to install requirements.txt. Is there a way to activate the virtualenv and then install my requirements from a single python script?

my code at the moment:

    if not os.path.exists(env_path):
        call(['virtualenv', env_path])

    else:
        print "INFO: %s exists." %(env_path)



    try:
        call(['source', os.path.join(env_path, 'bin', 'activate')])

    except Exception as e:
        print e

the error is "No such file directory"

Thanks

Upvotes: 3

Views: 3322

Answers (3)

Galoperidol
Galoperidol

Reputation: 63

Just want to expand the comment of phd, and add example for python3 version

exec(open('env/Scripts/activate_this.py').read(), {'__file__': 'env/Scripts/activate_this.py'})

Upvotes: 1

phd
phd

Reputation: 94473

source is a shell builtin command, not a program. It cannot and shouldn't be executed with subprocess. You can activate your fresh virtual env by executing activate_this.py in the current process:

if not os.path.exists(env_path):
    call(['virtualenv', env_path])
    activate_this = os.path.join(env_path, 'bin', 'activate_this.py')
    execfile(activate_this, dict(__file__=activate_this))

else:
    print "INFO: %s exists." %(env_path)

Upvotes: 4

Michael Speer
Michael Speer

Reputation: 4952

The source or . command causes the current shell to execute the given source file in it's environment. You'll need a shell in order to use it. This probably isn't as clean as you'd like it, since it uses a string instead of a list to represent the command, but it should work.

import subprocess

subprocess.check_call( [ 'virtualenv', 'env-dir' ] )

subprocess.check_call(
    ' . env-dir/bin/activate && pip install python-dateutil ',
    shell = True
)

Upvotes: 1

Related Questions