Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use pip.main() or subprocess.call() to invoke pip commands?

I am writing a program that needs to install dependencies using pip. What is the proper way to do it and why?

Ideally it needs to be platform agnostic, but the program will be running on a Linux machine.

Method 1: pip.main()

import pip
args = ['param1', 'param2']
version = 0.1
package = ['some_package=={}'.format(version)]
pip.main(['install'] + args + package) 

Method 2: subprocess.call()

import subprocess
import sys
version = 0.1
package = 'some_package'

subprocess.call([sys.executable, '-m', 'pip', 'install', '{}=={}'.format(package, version)])
like image 374
turnip Avatar asked Nov 01 '17 16:11

turnip


People also ask

How do I run a pip command in Python?

Run python get-pip.py . 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they're not installed already. Be cautious if you're using a Python install that's managed by your operating system or another package manager.

How do you use subprocess call in Python?

Return Value of the Call() Method from Subprocess in Python It may also raise a CalledProcessError exception. Now, use a simple example to call a subprocess for the built-in Unix command “ls -l.” The ls command lists all the files in a directory, and the -l command lists those directories in an extended format.

Can I run pip package from command line?

9) and Python 3 (>=3.4) installations. The pip command has options for installing, upgrading and deleting packages, and can be run from the Windows command line. By default, pip installs packages located in the Python Package Index (PyPI), but can also install from other indexes.


2 Answers

In general

Do not call somebody else's main() unless you want to give them ownership of the process. They could, for example, call sys.exit() or one of the os.exec*() functions. They could also install signal handlers, change the umask, or make all sorts of other global changes to your process's state. If you don't want them to do such things, you should run their code in a subprocess instead.

(Of course, library code can do all of the above just as easily, but it's considered "rude" to do so without documenting it, whereas the author of a main() function typically assumes they have the whole process to themself.)

For Pip in particular

pip.main() is not a public interface, and is unsupported. Use a subprocess.

like image 177
Kevin Avatar answered Oct 08 '22 04:10

Kevin


It depends. pip is undocumented and may not be backwards compatible. I recommend using subprocess instead, as the basic semantics of pip are unlikely to be changed in the near future.

like image 21
Daniel Avatar answered Oct 08 '22 05:10

Daniel