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>First off, if you use the universal import (<code>from m12345 import *</code>) then you just call the <code>my()</code> function and not the <code>m12345.my()</code> or else you will get a </p>

<blockquote>
  <p>NameError: name 'm12345' is not defined</p>
</blockquote>

<p>Secondly, you should add the following snippet in every script in which you want to have the ability of directly running it or not (when importing it).</p>

<pre><code>if "__name__" = "__main__":
    pass
</code></pre>

<p>PS. Add this to the 1st script ("m12345.py").
PS2. Avoid using the universal import method since it has the ability to mess the namespace of your script. (For that reason, it isn't considered best practice).</p>

<p><strong>edit:</strong> Is the m12345.py located in the python folder (where it was installed in your hard drive)? If not, then you should add the directory it is located in the sys.path with:</p>

<pre><code>import sys
sys.path.append(directory)
</code></pre>

<p>where directory is the string of the location where your m12345.py is located. Note that if you use Windows you should use <code>/</code> and not <code>\</code>.
However it would be much easier to just relocate the script (if it's possible).</p>

python ipython python-import