3

Hi I have a directory in the same folder as my main script called 'actions' in this folder there are several scripts that may be used at any time by the main script. I am at the point where I have the name of the script in the form of a string in a variable called VAR (for the sake of example). I would like to be able to import this file using the variable.

bs7280
  • 1,074
  • 3
  • 18
  • 32
  • 2
    Why don't the normal `import` or `from ... import` forms work for your use case? Trying to do dynamic imports almost always means there's a design flaw in your program. – Silas Ray Aug 01 '12 at 19:29
  • the program I am doing is working with, for lack of a better word, plugins that are all contained in one folder. Sorry if that wasn't very helpful but to me it seems to justify why I am dynamically importing scripts. – bs7280 Aug 01 '12 at 19:37

3 Answers3

3

If your aim is simply to execute the files, you can use

with open(filename) as f:
    exec(compile(f.read(), filename, "exec"))

or the Python 2.x function execfile().

If you actually want to import the modules using the full import machinery, you need an __init__.py in the directory actions, and can use something like

module = __import__("actions.foo")

to import actions/foo.py.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Or the methods in `importlib`. But still, the likely scenario is that there's a design flaw here. – Silas Ray Aug 01 '12 at 19:31
  • 2
    @sr2222: The usual use case is some kind of plugin system where plugins might be dynamically added to the directory. Seems fine to me. – Sven Marnach Aug 01 '12 at 19:35
  • @SvenMarnach yea its basically a plugin thing. For fun during the summer I tried to make a text based siri that basically uses, well, plugins which can be added to the folder at any time. Anywas it is literally about to be done so thanks so much. I would hug you if I could. – bs7280 Aug 01 '12 at 19:41
3

Use the __import__ function

__import__(str)
nims
  • 3,751
  • 1
  • 23
  • 27
  • 1
    thanks this worked but the other answer gets the check mark because it was much more in-depth of an answer mostly because he talked about the __init__.py which I was having trouble with before, and for anyone else who reads this page, it is very helpful info – bs7280 Aug 01 '12 at 19:38
0

2021 update: Python3.9.5's __import__() includes this message:

Import a module. Because this function is meant for use by the Python interpreter and not for general use, it is better to use importlib.import_module() to programmatically import a module.

So it then becomes:

from importlib import import_module
import_module(modulename_or_relative_filename)
Adam Smooch
  • 1,167
  • 1
  • 12
  • 27