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

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

问题描述

在Ruby中,我没有多次重复require(Python中的import),而是

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.

直接的traduction将类似于以下代码。无论如何,由于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天全站免登陆