Вопрос по python – Как загрузить все модули в папке?

215

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

/Foo
    bar.py
    spam.py
    eggs.py

Error: User Rate Limit Exceeded__init__.pyError: User Rate Limit Exceededfrom Foo import *Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded S.Lott
Error: User Rate Limit Exceeded"Explicit is better than implicit." yangmillstheory
Error: User Rate Limit ExceededinitError: User Rate Limit Exceeded balpha♦

Ваш Ответ

16   ответов
7

automodinit

__init__.pyyourpackage:

#!/usr/bin/env python
import os, pkgutil
__all__ = list(module for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]))

yourpackage:

from yourpackage import *

3

Error: User Rate Limit Exceeded__init__.pyError: User Rate Limit Exceeded__all__Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

...

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound,s/effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound package.

1

__init__.py

import importdir
importdir.do("Foo", globals())

5

import os

def loadImports(path):
    files = os.listdir(path)
    imps = []

    for i in range(len(files)):
        name = files[i].split('.')
        if len(name) > 1:
            if name[1] == 'py' and name[0] != '__init__':
               name = name[0]
               imps.append(name)

    file = open(path+'__init__.py','w')

    toWrite = '__all__ = '+str(imps)

    file.write(toWrite)
    file.close()

__init__.py__all__

Test

Foo.py
Bar.py

loadImports('Test/')
from Test import *

Test__init__.pyTest

__all__ = ['Foo','Bar']
16

.

Include the automodinit package into your setup.py dependencies. Replace all __init__.py files like this:
__all__ = ["I will get rewritten"]
# Don't modify the line above, or this line!
import automodinit
automodinit.automodinit(__name__, __file__, globals())
del automodinit
# Anything else you want can go after here, it won't get modified.

for x in __all__: import x

automodinit

Error: User Rate Limit Exceeded
4

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)
42

importlib

__init__.py__init__.py

import bar
import eggs
import spam

import os
for module in os.listdir(os.path.dirname(__file__)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

import Foo

Foo.bar
Foo.eggs
Foo.spam

Error: User Rate Limit Exceeded Evan Fosmark
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededdel os, тоже
Error: User Rate Limit Exceeded__import__Error: User Rate Limit Exceeded__all__Error: User Rate Limit Exceededfrom . import *Error: User Rate Limit Exceeded
__import__ не для общего использования, он используетсяinterpreterError: User Rate Limit Exceededimportlib.import_module()Error: User Rate Limit Exceeded
33

create an empty __init__.py file under Foo/ Execute
import pkgutil
import sys


def load_all_modules_from_dir(dirname):
    for importer, package_name, _ in pkgutil.iter_modules([dirname]):
        full_package_name = '%s.%s' % (dirname, package_name)
        if full_package_name not in sys.modules:
            module = importer.find_module(package_name
                        ).load_module(full_package_name)
            print module


load_all_modules_from_dir('Foo')

<module 'Foo.bar' from '/home/.../Foo/bar.pyc'>
<module 'Foo.spam' from '/home/.../Foo/spam.pyc'>
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededRuntimeWarningError: User Rate Limit Exceededimporter.find_module(package_name).load_module(package_name).
0

__all__ (add__init__.py

/Foo
    bar.py
    spam.py
    eggs.py
    __init__.py

# __init__.py
import os
import importlib
pyfile_extes = ['py', ]
__all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
del os, importlib, pyfile_extes
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededpy
4

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import os
import glob

all_list = list()
for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
    if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
        all_list.append(os.path.basename(f)[:-3])

__all__ = all_list  
331

.py__all____init__.py

from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
Error: User Rate Limit Exceeded Evan Fosmark
4

import os, glob

modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [os.path.basename(f)[:-3] for f in modules if not f.endswith("__init__.py")]
20

Python, include all files under a directory:

Make a folder /home/el/foo and make a file main.py under /home/el/foo Put this code in there:

from hellokitty import *
spam.spamfunc()
ham.hamfunc()

Make a directory /home/el/foo/hellokitty

Make a file __init__.py under /home/el/foo/hellokitty and put this code in there:

__all__ = ["spam", "ham"]

Make two python files: spam.py and ham.py under /home/el/foo/hellokitty

Define a function inside spam.py:

def spamfunc():
  print "Spammity spam"

Define a function inside ham.py:

def hamfunc():
  print "Upgrade from baloney"

Run it:

[email protected]:/home/el/foo$ python main.py 
spammity spam
Upgrade from baloney
1

__init__.py__init__.py

122

__all____init__.py

__all__ = ["bar", "spam", "eggs"]

Error: User Rate Limit Exceededmy answerError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Evan Fosmark
Error: User Rate Limit Exceededgithub.com/namgivu/python-import-all/blob/master/error_app.pyError: User Rate Limit Exceeded
3

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

Похожие вопросы