Calling python scripts from within python

It took me a while to find this solution, so I want others to see it.

I wanted to write a python script to create virtual envs and install modules inside it. Unfortunately pip doesn't play well with subprocess as described here: https://github.com/pypa/pip/issues/610

My answer is already in this thread, but I wanted to describe it in more detail below

+3


source to share


1 answer


Basically, the problem is that pip is still using the python executable that the original python called. To fix this, you need to remove it from the passed environment variables. Here's the solution:

#!/usr/bin/python3
import os
import subprocess

python_env_var = {"_", "__PYVENV_LAUNCHER__"}
CMD_ENVIRONMENT = {name: value for (name, value) in os.environ.items() 
                   if name not in python_env_var}  
subprocess.call('./pip install -r requirements.txt', shell=True, 
                env=CMD_ENVIRONMENT)

      



Tested on Mac, ubuntu 14.04 and Windows with python 3

This same problem can easily exist for a variety of situations - I will remove this variable from now on to prevent this behavior when working with

virtualenv
+3


source







All Articles