检查是否安装了 Python 包

新手上路,请多包涵

在 Python 脚本中检查包是否已安装的好方法是什么?我知道解释器很容易,但我需要在脚本中完成。

我想我可以检查系统上是否有在安装过程中创建的目录,但我觉得有更好的方法。我试图确保安装了 Skype4Py 包,如果没有,我会安装它。

我完成检查的想法

  • 检查典型安装路径中的目录
  • 尝试导入包,如果抛出异常,则安装包

原文由 Kevin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 428
2 个回答

如果你的意思是 python 脚本,只需执行以下操作:

Python 3.3+ 使用 sys.modules 和 find_spec

 import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

蟒蛇 3:

 try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

蟒蛇2:

 try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

原文由 Christopher 发布,翻译遵循 CC BY-SA 4.0 许可协议

从 Python 3.3 开始,您可以使用 find_spec() 方法

import importlib.util

# For illustrative purposes.
package_name = 'pandas'

spec = importlib.util.find_spec(package_name)
if spec is None:
    print(package_name +" is not installed")

原文由 ice.nicer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题