how, inside a python script can I install packages using pip? I don't use the os.system, I want to import pip and use it.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
pip.main() no longer works in pip version 10 and above. You need to use:
For backwards compatibility you can use:
You can run pip inside a python script:
If you are behind a proxy, you can install a module within code as follow...
This is a comment to this post that didn't fit in the space allotted to comments.
Note that the use case of installing a package can arise inside
setup.py
itself. For example, generatingply
parser tables and storing them to disk. These tables must be generated beforesetuptools.setup
runs, because they have to be copied tosite_packages
, together with the package that is being installed.There does exist the
setup_requires
option ofsetuptools.setup
, however that does not install the packages.So a dependency that is required both for the installation process and for the installed package will not be installed this way.
Placing such a dependency inside
install_requires
does not always work as expected. Even if it worked, one would have to pass some function tosetuptools.setup
, to be run between installation of dependencies insetup_requires
and installation of the package itself. This approach is nested, and thus against PEP 20.So the two flat approaches that remain, are:
run
setup.py
twice, either automatically (preferred), or manually (by notifying the user that the tables failed to build prior tosetuptools.setup
.first call
pip
(or some other equivalent solution), in order to install the required dependencies. Then proceed with building the tables (or whatever pre-installation task is necessary), and callsetuptools.setup
last.Personally, I prefer No.2, because No.2 can be confusing to a user observing the console output during installation, unless they already know the intent of calling
setuptools.setup
twice.Besides, whatever rights are needed for installation (e.g., root, if so desired), are certainly present when
setup.py
is run (and exactly then). Sosetup.py
could be considered as the "canonical" use case for this type of action.I used the os.system to emulate the terminal installing a pip module, (I know os.system is deprecated, but it still works and it is also the easiest way to do it), E.G I am making a Game Engine which has multiple python scripts that all use Pygame, in the startup file I use this code to install pygame onto the user's system if they don't have it:
Unfortunately, I don't know how to install pip if they don't have it so this script is dependent on pip.
I think those answers are outdated. In fact you can do:
and insert any additional args in the list that you pass to main(). It returns 0 (failed) or 1 (success)
Jon