Leo
Leo

Reputation: 1809

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

Upvotes: 1

Views: 91

Answers (2)

geo1230
geo1230

Reputation: 252

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

Upvotes: 2

Anant Bhardwaj
Anant Bhardwaj

Reputation: 121

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

or

from m12345 import *

Upvotes: 1

Related Questions