35

在 Ruby 中,我不会多次重复“require”(Python 中的“import”)这个词

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

所以它会遍历一组“libs”和“require”(导入)它们中的每一个。现在我正在编写一个 Python 脚本,我想做类似的事情。有没有办法,或者我需要为所有这些写“导入”。

直截了当的“翻译”类似于以下代码。无论如何,由于 Python 不导入命名为字符串的库,因此它不起作用。

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

提前致谢

4

7 回答 7

66

For known module, just separate them by commas:

import lib1, lib2, lib3, lib4, lib5

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.

于 2010-07-15T22:39:02.883 回答
26

试试这个:

import lib1, lib2, lib3, lib4, lib5

您还可以通过这种方式更改导入它们的名称,如下所示:

import lib1 as l1, lib2 as l2, lib3, lib4 as l4, lib5
于 2010-07-15T22:35:44.457 回答
8

import lib1, lib2, lib3, lib4, lib5

于 2010-07-15T22:31:14.400 回答
6

if you want multi-line:

from englishapps.multiple.mainfile import (
    create_multiple_,
    get_data_for_multiple
)
于 2020-12-16T16:54:56.497 回答
4

__import__您可以使用该函数从包含模块名称的字符串导入。

requirements = [lib1, lib2, lib3, lib4, lib5]
for lib in requirements:
    x = __import__(lib)
于 2010-07-15T22:36:44.543 回答
3

You can use __import__ if you have a list of strings that represent modules, but it's probably cleaner if you follow the hint in the documentation and use importlib.import_module directly:

import importlib
requirements = [lib1, lib2, lib3, lib4, lib5]
imported_libs = {lib: importlib.import_module(lib) for lib in requirements}

You don't have the imported libraries as variables available this way but you could access them through the imported_libs dictionary:

>>> requirements = ['sys', 'itertools', 'collections', 'pickle']
>>> imported_libs = {lib: importlib.import_module(lib) for lib in requirements}
>>> imported_libs
{'collections': <module 'collections' from 'lib\\collections\\__init__.py'>,
 'itertools': <module 'itertools' (built-in)>,
 'pickle': <module 'pickle' from 'lib\\pickle.py'>,
 'sys': <module 'sys' (built-in)>}

>>> imported_libs['sys'].hexversion
50660592

You could also update your globals and then use them like they were imported "normally":

>>> globals().update(imported_libs)
>>> sys
<module 'sys' (built-in)>
于 2017-08-27T12:54:35.250 回答
1

I just learned from a coworker today that, according to the PEP 8 Style Guide, imports in Python should actually be written on separate lines:

import os
import sys

The style guide calls import sys, os wrong.

于 2021-09-28T17:21:59.977 回答