我正在编写一个需要使用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命令?
发布评论