在python中导入文件时出现导入错误 [英] Import error while importing a file in python
问题描述
我在同一位置有两个文件,分别是"hello-depend.py"和"second-package.py"
I have two files in the same location namely 'hello-depend.py' and 'second-package.py'
hello-depend.py
class HelloDepend():
def depend():
print "depend"
second-package.py
from hello-depend import HelloDepend
class SecondPackage():
def second():
print "second"
h = HelloDepend()
h.depend()
if \__name__ == '\__main__':
s = SecondPackage()
s.second()
我需要从second-package.py为hello-depend.py创建对象.我绑上面的方法.但是我在导入"hello-depend"时收到"语法错误".
I need to create object for hello-depend.py from second-package.py. i tied with above method. But i am getting 'syntax error' while importing 'hello-depend'.
错误:
文件"second-package.py",第1行
File "second-package.py", line 1
import hello-depend
^
SyntaxError:语法无效
SyntaxError: invalid syntax
所以我尝试了以下方法.
So i tried with below method.
import importlib
import importlib
importlib.import_module('hello-depend')
importlib.import_module('hello-depend')
但是我得到的是"全局名称'HelloDepend'未定义'
but i am getting "global name 'HelloDepend' not defined'
请帮助我解决这个问题.
Please help me in solving this.
注意:我需要在不更改文件名的情况下执行此操作.
Note: I need to do this without changing file name.
推荐答案
问题在此处-
.Python尝试将其视为减号,并且 hello-dependent
才不是有效的标识符.
Problem is -
here. Python tries to treat it as minus symbol and hello-depend
is not a valid identifier then.
尝试通过将-替换为下划线( _
)
Try to rename your file by replacing - with underscore (_
)
如果您无法更改文件名,无论出于何种原因,都可以
If you just cant change the file names, whatever the reason may be, then you can do
execfile('hello-depend.py')
请注意,这不会导入文件,它将使所有文件的全局变量都进入您自己的作用域,因此不建议他使用它来解决此问题.
Note that this does not import the file, it would get all the file globals into your own scope, and his highly unrecommended to solve this problem.
这篇关于在python中导入文件时出现导入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!