如何在 Python 中进行多次导入? [英] How to do multiple imports in Python?

查看:28
本文介绍了如何在 Python 中进行多次导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我没有多次重复要求"(Python 中的导入")词,而是重复

In Ruby, instead of repeating the "require" (the "import" in Python) word lots of times, I do

%w{lib1 lib2 lib3 lib4 lib5}.each { |x| require x }

因此它遍历libs"和require"(导入)集合中的每一个.现在我正在编写一个 Python 脚本,我想做类似的事情.有没有办法,或者我需要为所有这些编写导入".

So it iterates over the set of "libs" and "require" (import) each one of them. Now I'm writing a Python script and I would like to do something like that. Is there a way to, or do I need to write "import" for all of them.

直接的推导"类似于以下代码.无论如何,由于 Python 不导入以字符串命名的库,因此它不起作用.

The straight-forward "traduction" would be something like the following code. Anyway, since Python does not import libs named as strings, it does not work.

requirements = [lib1, lib2, lib3, lib4, lib5]
for lib in requirements:
    import lib

提前致谢

推荐答案

对于已知模块,用逗号隔开:

For known module, just separate them by commas:

import lib1, lib2, lib3, lib4, lib5

如果你真的需要基于动态变量以编程方式导入,你的 ruby​​ 的直译是:

If you really need to programmatically import based on dynamic variables, a literal translation of your ruby would be:

modnames = "lib1 lib2 lib3 lib4 lib5".split()
for lib in modnames:
    globals()[lib] = __import__(lib)

尽管在您的示例中不需要这样做.

Though there's no need for this in your example.

这篇关于如何在 Python 中进行多次导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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