0

I'd like to create a virtual environment and install a script from within a python script. Is there a way to do that? Similar to

import pip
pip.main(['install', 'django'])
lmr2391
  • 571
  • 1
  • 7
  • 14
  • Hope this post helps you https://stackoverflow.com/questions/12966147/how-can-i-install-python-modules-programmatically-through-a-python-script/13016849 – Yurii Kramarenko Aug 07 '18 at 13:24

2 Answers2

0

You can create a file called 'requirements.txt' in which you write all the libraries you want to install

requirements.txt:

django

now create your python file for your script example.py:

import os

if __name__ == "__main__":

    name_env = 'my_env'

    create_virtual_env = 'python3 -m venv {}'.format(name_env)
    activate_virtual_env = 'source {}/bin/activate'.format(name_env)
    update_pip = 'curl https://bootstrap.pypa.io/get-pip.py | python'
    instal_required_libraries = 'pip3 install -r ./requirements.txt'

    command = '{} && {} && {} && {}'.format(create_virtual_env, activate_virtual_env, update_pip, instal_required_libraries)
    os.system(command)

you need to use && to separate your command in order to wait the end of the previous command

finaly you can run your script:

python3 example.py

I hope it will help you

Diane Delallée
  • 123
  • 2
  • 9
  • Hey Diane! Thanks for your answer. But I was asking for a solution to do that using `pipenv` instead of `pip`. Of course, a similar approach would lead to success. But it would be nicer to do that by calling python code directly instead of using python to construct command line code – lmr2391 Aug 09 '18 at 07:53
0

Pipenv is now the official package manager for Python. You can use pipenvlib. This library makes it easy to programmatically interact with, introspect, manipulate Pipenv projects. It also allows you examine dependencies and requirements of a project, as well as install/uninstall packages from Python directly.

Ahmed
  • 1,008
  • 12
  • 15