我应该使用pip.main()还是subprocess.call()来调用pip命令? [英] Should I use pip.main() or subprocess.call() to invoke pip commands?

查看:154
本文介绍了我应该使用pip.main()还是subprocess.call()来调用pip命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要使用pip安装依赖项的程序.正确的方法是什么?为什么?

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

理想情况下,它必须与平台无关,但是该程序将在Linux机器上运行.

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

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

方法2:subprocess.call()

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

subprocess.call([sys.executable, '-m', 'pip', 'install', '{}=={}'.format(package, version)])

推荐答案

一般而言

除非您要授予他人对该进程的所有权,否则请不要称呼他人的main().例如,他们可以调用sys.exit()os.exec*()函数之一.他们还可以安装信号处理程序,更改umask或对进程状态进行各种其他全局更改.如果您不希望他们这样做,则应该在子进程中运行他们的代码.

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.

(当然,库代码可以轻松地完成上述所有操作,但是在没有文档说明的情况下这样做是不礼貌的",而main()函数的作者通常假定他们自己掌握了整个过程)

(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.)

pip.main()不是公共接口,不受支持.使用子进程.

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

这篇关于我应该使用pip.main()还是subprocess.call()来调用pip命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆