简体   繁体   English

如何在ipyhon中导入脚本作为模块?

[英]how to import scripts as modules in ipyhon?

So, I've two python files: 所以,我有两个python文件:

the 1st "m12345.py" 第1个“m12345.py”

def my():
    return 'hello world'

the 2nd "1234.py": 第二个“1234.py”:

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

On ipython I try to exec such cmds: 在ipython上我尝试执行这样的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? 请帮助如何将第一个文件添加为第二个模块?

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 首先,如果您使用通用导入( from m12345 import * ),那么您只需调用my()函数而不是m12345.my() ,否则您将得到一个

NameError: name 'm12345' is not defined NameError:未定义名称“m12345”

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. PS。 Add this to the 1st script ("m12345.py"). 将其添加到第一个脚本(“m12345.py”)。 PS2. 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)? 编辑: m12345.py是否位于python文件夹中(它安装在硬盘中)? If not, then you should add the directory it is located in the sys.path with: 如果没有,那么你应该添加它在sys.path中的目录:

import sys
sys.path.append(directory)

where directory is the string of the location where your m12345.py is located. 其中directory是m12345.py所在位置的字符串。 Note that if you use Windows you should use / and not \\ . 请注意,如果您使用Windows,则应使用/而不是\\ However it would be much easier to just relocate the script (if it's possible). 但是,重新定位脚本会更容易(如果可能的话)。

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__) . 您必须通过调用m12345 = imp.new_module('m12345')创建一个新模块(例如m12345 ),然后通过调用exec(open('path/m12345.py').read(), m12345.__dict__)该模块中的python脚本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 *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM