1

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

0

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that worked. Why did somebody downvote this?
Good question. I'm not sure. I'm guessing someone out there prefers importlib. If you know your code, and you know that your users are going to be careful to only import modules that can be imported, I don't personally think it matters. I personally prefer the simplicity of exec'ing a string :-)
0

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

Even the docs say: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module(). IMO it's better to close the question as this has been asked many times.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.