0

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.pywould be something like:

import /commands/*

Thanks :D

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

from commands import * Does not work.

2 Answers2

0

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
Noufal Ibrahim
  • 69,212
  • 12
  • 131
  • 165
  • Why did you reopen the question? – Padraic Cunningham Sep 05 '16 at 20:00
  • 1
    This question specifically asks about importing directory full of modules. The note that he wants to implement each command as a separate module suggested (to me) a plugin like architecture which will dynamically load up the modules in the directory without manually editing the `__init__.py` files. The question which this was linked to simply mentioned the `__init__.py` business and how modules are loaded when packages are imported. While valid, it didn't, to me, address what this question was looking for. That's why I reopened it. – Noufal Ibrahim Sep 06 '16 at 04:35
  • I would have mentioned this but there was no clear way to "suggest reopening". Clicking on reopen automatically reopened the question. – Noufal Ibrahim Sep 06 '16 at 04:36
-2

Import each separately with: from commands import bar and from commands import foo

from commands import * Does not work.

  • But your question was _"...without importing each separately"_ so this isn't the answer. `from command import bar, foo` would be more compact and its also common to put something like `__all__ = ["foo", "bar']` into _commands/__init__.py_ if the module thinks all uses will want the modules. – tdelaney Sep 05 '16 at 20:16