0

I am trying to run activate.sh file to set environment paths for vitrual environment from python but I am not able to run source files from python. Is there any way to do that

My source is here

if sys.argv[1]=='-a':
        os.system('. activate.sh')
    elif sys.argv[1]=='-d':
        os.system('. deactivate.sh')
    else:
        print('You only have -a, -d as options')
tushar_ecmc
  • 186
  • 2
  • 21
  • Any reason not to run activate.sh **normally** (from *shell*)? https://stackoverflow.com/questions/54420483/activating-virtualenv-from-within-python-script/54420696#54420696 – CristiFati Feb 08 '19 at 09:45
  • I am working on something in which I need to automate this from python. – tushar_ecmc Feb 08 '19 at 11:07

2 Answers2

0

You can use subprocess, which will run the bash script. But be careful, only use trusted bash files. So the code should be:

import subprocess
if sys.argv[1]=='-a':
        subprocess.call("activate.sh", shell=True)
    elif sys.argv[1]=='-d':
        subprocess.call("deactivate.sh", shell=True)
    else:
        print('You only have -a, -d as options')
Marin Gömöri
  • 67
  • 1
  • 1
  • 2
0

This will activate the virtualenv on a new bash session.

Assuming things like platform: linux, new bash session is OK.

import os
# os.execv("/bin/bash", ["bash", "-c", "source ve/bin/activate;bash"])
os.execv("/bin/bash", ["bash", "-c", "source /path/to/activate;bash"])
han solo
  • 6,390
  • 1
  • 15
  • 19