Installing python module within code
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:32 Accepted answer (Score 522)
01:11 Answer 2 (Score 427)
01:27 Answer 3 (Score 86)
02:07 Answer 4 (Score 37)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/1233...
Accepted answer links:
[Most other answers presented here are not supported by pip]: https://pip.pypa.io/en/latest/user_guide...
Answer 3 links:
[How to refresh sys.path?]: https://stackoverflow.com/questions/2538...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pip #pythonmodule #pypi
#avk47
ACCEPTED ANSWER
Score 602
The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.
Use sys.executable to ensure that you will call the same pip associated with the current runtime.
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
ANSWER 2
Score 440
You can also use something like:
import pip
def install(package):
if hasattr(pip, 'main'):
pip.main(['install', package])
else:
pip._internal.main(['install', package])
# Example
if __name__ == '__main__':
install('argh')
ANSWER 3
Score 92
If you want to use pip to install required package and import it after installation, you can use this code:
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportError:
import pip
pip.main(['install', package])
finally:
globals()[package] = importlib.import_module(package)
install_and_import('transliterate')
If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.
ANSWER 4
Score 47
This should work:
import subprocess
import sys
def install(name):
subprocess.call([sys.executable, '-m', 'pip', 'install', name])