I am aware that this is in principle a question that has been asked a lot already. But I have a more specific question within this general thing of importing external files.
So, I have a few external files that each contain a database - different grammars for parsing text - that is required for my main script to run. I want to pass the external databse-scripts through as a command line argument. A single one per call of the main script. So I wrote the following sequence at the top of my main script:
extGrammar = sys.argv[-1]
import extGrammar
So my reasoning was to give the variable extGrammar the name of the command line argument that corresponds to whatever name the database file in question has, and then import that file. Just as if I had written
import grammar1
if I had an external file grammar1.py
But I get the error "ImportError: No module named extGrammar"
which I don't understand. Where is the flaw in my reasoning and what is a correct way of doing this?
Thanks
2 Answers 2
Try:
import importlib
extGrammar = importlib.import_module(extGrammar)
or:
exec ("import " + extGrammar)
The problem is that python is not realizing that this is a variable containing a string referring to a package. Instead it looks for a package called "extGrammar" in the path.
2 Comments
You need to call the builtin function, __import__, not the import statement, as the Python language parses the latter as a direct import (the variable name is therefore treated as a module, with obvious result). To import a module that is referred by name via a variable, you need the function, not the statement.
1 Comment
importlib.import_module(). IMO it's better to close the question as this has been asked many times.