在运行时使用 Python 模块

Use Python module on the runtime

import os
import sys

#run get-pip.py
os.system("python get-pip.py")

#try to import pip
try:
    __import__('pip')
except ImportError:
    input('Could not install pip, please enter any key to quit this window.')
    sys.exit()

#install selenium
def install(package):
    pip.main(['install', package])

if __name__ == '__main__':
    install('selenium')

当我 运行 这个脚本时,我得到:

NameError: name 'pip' is not defined

好像__import__('pip')没有导入pip,如何让它导入pip?

当我 运行 这段代码安装 pip 时, try 也没有抛出任何异常。我在尝试安装 selenium 时收到此错误,因为我认为由于某种原因 pip 未导入 try

您应该使用标准 import pip 除非您试图定义要动态导入的模块。如果未安装 pip,它仍会引发 ImportError。