Leo Leo - 1 year ago 134
Python Question

how to import scripts as modules in ipyhon?

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

On ipython I try to exec such cmds:


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 Source

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

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

If you want the module to be in system path, you can add

sys.modules['m12345'] = m12345

After this you can do

import m12345


from m12345 import *
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download