简体   繁体   中英

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. 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:

import /commands/*

Thanks :D

Solution: Import each separately with: from commands import foo, bar

from commands import * Does not work.

If you're using python3, the importlib module can be used to dynamically import modules. On python2.x, there is the __import__ function but I'm not very familiar with the semantics. As a quick example,

I have 2 files in the current directory

# 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 * Does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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