Python - import external file via command line
Question: 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


Answer: You need to call the builtin _function_ ,
[`__import__`](https://docs.python.org/2/library/functions.html#__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.

