Search code examples
pythonsubprocessvirtualenvwrapper

virtualenvwrapper, add2virtualenv from python script


I got a project with files like it:

├── main_folder
    ├── my_folder
          ├── my_file.py
    ├── main_file.py

Inside main_file.py i am trying to run a below command:

import subprocess
subprocess.getstatusoutput(f'add2virtualenv FULL_PATH_TO_PROJECT/main_folder')

but as a response i am getting (127, '/bin/sh: 1: add2virtualenv: not found')
How can i solve it so i could use inside a my_file.py below line:

from main_file import something

Solution

  • add2virtualenv and other virtualenvwrapper's commands are shell functions defined in virtualenvwrapper.sh; to call them you need first to source virtualenvwrapper.sh in the same shell. Also be warned they work with bash or zsh but not with /bin/sh.

    So my advice is to create a bash script:

    #! /usr/bin/env bash
    source `which virtualenvwrapper.sh`
    add2virtualenv "$1"
    

    and call it as a subprocess:

    subprocess.getstatusoutput(f'myscript FULL_PATH_TO_PROJECT/main_folder')