how to import scripts as modules in ipyhon?
Question: So, I've two python files:

the 1st "m12345.py"

    
    
    def my():
        return 'hello world'
    

the 2nd "1234.py":

    
    
    from m12345 import *
    a = m12345.my()
    print(a)
    

On ipython I try to exec such cmds:

    
    
    exec(open("f:\\temp\\m12345.py").read())
    exec(open("f:\\temp\\1234.py").read())
    

the error for the 2nd command is:

    
    
    ImportError: No module named 'm12345'
    

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


Answer: First off, if you use the universal import (`from m12345 import *`) then you
just call the `my()` function and not the `m12345.my()` or else you will get a

> NameError: name 'm12345' is not defined

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).

    
    
    if "__name__" = "__main__":
        pass
    

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).

**edit:** 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:

    
    
    import sys
    sys.path.append(directory)
    

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

