Variables in import statement python
<p>I'm trying to convert a script I had from bash to python. The way the program worked is that it had a Master script in the top folder and then in the subfolder Scripts a series of smaller, more specialised scripts. These smaller scripts might have names such as foo_bar.x, bar_foo.x, foo_baz.x, foo_qux.x, bar_qux.x, and so on. The Master script would collect the variables (as defined in files or from command line arguments) and execute the appropriate script with this sort of syntax:</p>

<pre><code>VAR1=foo
VAR2=bar
./Scripts/${VAR1}_${VAR2}.x
</code></pre>

<p>This would execute Scripts/foo_bar.x</p>

<p>Now I'm trying to do the same but in python. The scripts are now modules in the folder Modules named foo_bar.py, foo_qux.py and so on. For now, the only thing they have is:</p>

<pre><code>def test():
        print "This is foo_bar."
</code></pre>

<p>(or whichever).</p>

<p>If use these commands, this happens:</p>

<pre><code>&gt;&gt;&gt; import Modules.foo_bar
&gt;&gt;&gt; Modules.foo_bar.test()
This is foo_bar.
&gt;&gt;&gt; import Modules.foo_qux
&gt;&gt;&gt; Modules.foo_qux.test()
This is foo_qux.
&gt;&gt;&gt; a = Modules.foo_bar
&gt;&gt;&gt; a.test()
This is foo_bar.
</code></pre>

<p>Which is fine. However, I can't get the syntax right if I want to use variables in the import statement. The first variable is defined as the string output of a command, and the second is a dictionary entry. Trying to use them in an import command gives an error.</p>

<pre><code>&gt;&gt;&gt; var1 = a_file.read_value()
&gt;&gt;&gt; print var1
foo
&gt;&gt;&gt; print dict['var2']
bar
&gt;&gt;&gt; import Modules.var1_dict['var2']
  File "&lt;stdin&gt;", line 1
    import Modules.var1_dict['var2']
                            ^
SyntaxError: invalid syntax
</code></pre>

<p>I assume it's a question of having the correct quotes or parentheses to properly invoke the variables. I've tried a bunch of combinations involving single quotes, curly brackets, square brackets, whatever, but no dice. What am I missing?</p>

<p>You can use the <code>importlib</code> library. And use like this:</p>

<pre><code>...
import importlib
...

    function_call = 'Modules.' + var1 + dict['var2']
    function_call = importlib.import_module(function_call) 
    function_call.test()
</code></pre>

python python-2.7