Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run pip in python idle

I am curious about running pip. Everytime I ran pip in command shell in windows like that

c:\python27\script>pip install numpy

But, I wondered if I can run it in python idle.

import pip
pip.install("numpy")

Unfortunately, it is not working.

like image 292
Hyun-geun Kim Avatar asked Jan 25 '16 09:01

Hyun-geun Kim


3 Answers

Still cannot comment so I added another answer. Pip has had several entrypoints in the past. And it's not recommended to call pip directly or in-process (if you still want to do it, "runpy" is kind of recommended):

import sys
import runpy

sys.argv=["pip", "install", "packagename"]
runpy.run_module("pip", run_name="__main__")

But this should also work:

try:
    from pip._internal import main as _pip_main
except ImportError:
    from pip import main as _pip_main
_pip_main(["install", "packagename"])
like image 163
rtrrtr Avatar answered Oct 26 '22 04:10

rtrrtr


This question is, or should be, about how to run pip from a python program. IDLE is not directly relevant to this version of the quesiton.

To expand on J. J. Hakala's comment: a command-line such as pip install pillow is split on spaces to become sys.argv. When pip is run as a main module, it calls pip.main(sys.argv[1:]). If one imports pip, one may call pip.main(arg_line.split()), where arg_line is the part of the command line after pip.

Last September (2015) I experimented with using this unintended API from another python program and reported the initial results on tracker issue 23551. Discussion and further results followed.

The problem with executing multiple commands in one process is that some pip commands cache not only sys.path, which normally stays constant, but also the list of installed packages, which normally changes. Since pip is designed to run one command per process, and then exit, it never updates the cache. When pip.main is used to run multiple commands in one process, commands given after the caching may use a stale and no-longer-correct cache. For example, list after install shows how things were before the install.

A second problem for a program that wants to examine the output from pip is that it goes to stdout and stderr. I posted a program that captures these streams into program variables as part of running pip.

Using a subprocess call for each pip command, as suggested by L_Pav, though less efficient, solves both problems. The communicate method makes the output streams available. See the subprocess doc.

like image 31
Terry Jan Reedy Avatar answered Oct 26 '22 03:10

Terry Jan Reedy


At moment there are no official way to do it, you could use pip.main but you current idle session will not 'see' this installed package.

There been a lot a discussion over how to add a "high level" programmatic API for pip, it's seems promising.

like image 25
fn. Avatar answered Oct 26 '22 04:10

fn.