[英]How to import a.b in python?
I try to use __init__.py
. 我尝试使用
__init__.py
。
My directory: 我的目录:
sam@sam-M51Kr:~/code/python$ tree
.
|-- __init__.py
|-- lib
| |-- __init.py
| |-- sam_lib.py
| `-- sam_lib.pyc
`-- test.py
1 directory, 5 files
sam@sam-M51Kr:~/code/python$
All my __init__.py
are empty. 我所有的
__init__.py
都是空的。
My lib/sam_lib.py
: 我的
lib/sam_lib.py
:
k='hello!'
My test.py
: 我的
test.py
:
import python.lib.sam_lib
print(sam_lib.k)
When I run: 当我跑步时:
sam@sam-M51Kr:~/code/python$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
import python.lib.sam_lib
ImportError: No module named python.lib.sam_lib
sam@sam-M51Kr:~/code/python$
How to solve it with syntax import xx
? 如何使用语法
import xx
解决它?
Should I use __init.py__
? 我应该使用
__init.py__
吗?
============================== ==============================
I revise lib/__init.py
to lib/__init__.py
我将
lib/__init.py
修改为lib/__init__.py
I try to revise test.py
: 我尝试修改
test.py
:
from . import lib.sam_lib as sam_lib
print(sam_lib.k)
It will cause an error: 它将导致错误:
sam@sam-M51Kr:~/code/python$ python test.py
File "test.py", line 1
from . import lib.sam_lib as sam_lib
^
SyntaxError: invalid syntax
sam@sam-M51Kr:~/code/python$
And it is ok when I revise to: 当我修改为:
import lib.sam_lib as sam_lib
print(sam_lib.k)
Your code is wrong at different levels 您的代码在不同级别上是错误的
__init.py
should be __init__.py
__init.py
应该是__init__.py
import abc
the cx
object must be accessed using abcx
unless you used import abc as c
import abc
,必须使用abcx
访问cx
对象,除非您将import abc as c
To fix the code, use: 要修复代码,请使用:
import lib.sam_lib as sam_lib
print(sam_lib.k)
Note that import python.lib.sam_lib as sam_lib
or from .lib import sam_lib
would have worked if test.py is imported as a module as in import python.test
from a code in the upper level directory, not when you run test.py directly. 请注意,如果将test.py作为模块
import python.test
从上层目录中的代码from .lib import sam_lib
中import python.lib.sam_lib as sam_lib
或from .lib import sam_lib
将起作用,而不是在运行test.py时直。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.