how to import scripts as modules in ipyhon?
<p>So, I've two python files:</p>

<p>the 1st "m12345.py"</p>

<pre><code>def my():
    return 'hello world'
</code></pre>

<p>the 2nd "1234.py":</p>

<pre><code>from m12345 import *
a = m12345.my()
print(a)
</code></pre>

<p>On ipython I try to exec such cmds:</p>

<pre><code>exec(open("f:\\temp\\m12345.py").read())
exec(open("f:\\temp\\1234.py").read())
</code></pre>

<p>the error for the 2nd command is:</p>

<pre><code>ImportError: No module named 'm12345'
</code></pre>

<p>Please, help how to add the 1st file as a module for the 2nd?</p>

<p>You have to create a new module (for example <code>m12345</code>) by calling <code>m12345 = imp.new_module('m12345')</code>  and then exec the python script in that module by calling <code>exec(open('path/m12345.py').read(), m12345.__dict__)</code>. See the example below:</p>

<pre><code>import imp
pyfile = open('path/m12345.py').read()
m12345 = imp.new_module('m12345')
exec(pyfile, m12345.__dict__)
</code></pre>

<p>If you want the module to be in system path, you can add</p>

<pre><code>sys.modules['m12345'] = m12345
</code></pre>

<p>After this you can do</p>

<pre><code>import m12345
</code></pre>

<p>or</p>

<pre><code>from m12345 import *
</code></pre>

python ipython python-import