简体   繁体   English

导入整个python文件文件夹

[英]Import a whole folder of python files

I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. 我正在用python 3做一个机器人,希望它可以轻松地扩展,所以我有一个中央文件,然后每个命令一个。 I wish to know if there is a way to import a sub-directory full of modules without importing each separately. 我想知道是否有一种方法可以导入一个充满模块的子目录,而不必分别导入每个模块。 For example: 例如:

example
├── commands
│   ├── bar.py
│   └── foo.py
└── main.py

And the code in main.py would be something like: 而且main.py的代码将类似于:

import /commands/*

Thanks :D 感谢:D

Solution: Import each separately with: from commands import foo, bar 解决方案:使用以下from commands import foo, bar分别导入每个对象: from commands import foo, bar

from commands import * Does not work. from commands import *不起作用。

If you're using python3, the importlib module can be used to dynamically import modules. 如果您使用的是python3,则可以使用importlib模块动态导入模块。 On python2.x, there is the __import__ function but I'm not very familiar with the semantics. 在python2.x上,有__import__函数,但是我对语义不是很熟悉。 As a quick example, 举个简单的例子

I have 2 files in the current directory 我在当前目录中有2个文件

# a.py
name = "a"

and

# b.py
name = "b"

In the same directory, I have this 在同一目录中,我有这个

import glob
import importlib

for f in glob.iglob("*.py"):
    if f.endswith("load.py"):
        continue
    mod_name = f.split(".")[0]
    print ("importing {}".format(mod_name))
    mod = importlib.import_module(mod_name, "")
    print ("Imported {}. Name is {}".format(mod, mod.name))

This will print 这将打印

importing b Imported <module 'b' from '/tmp/x/b.py'>. 
Name is b
importing a Imported <module 'a' from '/tmp/x/a.py'>. 
Name is a

Import each separately with: from commands import bar and from commands import foo 分别使用以下from commands import barfrom commands import barfrom commands import foo

from commands import * Does not work. from commands import *不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM