简体   繁体   English

如何在python中导入模块

[英]how to import modules in python

I'm making a lambda function in python.我正在 python 中创建一个 lambda 函数。 Here is the current structure of my project.这是我项目的当前结构。

lambda/
|-- package_name/
|   |-- __init__.py
|   |-- lambda_function.py
|   |-- a.py 
|   |-- utils.py
|
|-- tests/
|   |-- __init__.py
|   |-- test_main.py
|-- setup.py
|-- README

I would like to import lambda_function.py and a.py in test_main.py我想在 test_main.py 中导入 lambda_function.py 和 a.py

I tried我试过

from a import *
import a
from package_name import a

and some others, but nothing is working.和其他一些,但没有任何效果。

Could you explain me what is the right solution, and why what I tried actually deosn't work ?你能解释一下什么是正确的解决方案,为什么我尝试过的实际上不起作用?

If your working directory is lambda , try:如果您的工作目录是lambda ,请尝试:

from package_name import a

There are some pre-determined places where python will look for packages. python会在一些预先确定的地方寻找包。 Usually the working directory is one of them.通常工作目录就是其中之一。

See: https://leemendelowitz.github.io/blog/how-does-python-find-packages.html参见: https : //leemendelowitz.github.io/blog/how-does-python-find-packages.html

I would recommend you to read about import in Python docs :我建议您阅读 Python 文档中的import
Python 3: https://docs.python.org/3/reference/import.html Python 2: https://docs.python.org/2/tutorial/modules.html Python 3: https : //docs.python.org/3/reference/import.html Python 2: https : //docs.python.org/2/tutorial/modules.html

but you can import it relatively using : import * from ../package_name/a , import * from ../package_name/lambda_function但是您可以使用以下方法相对导入它: import * from ../package_name/a , import * from ../package_name/lambda_function

or you will need to add package_name folder to the sys.path and then just import * from a as you tried .或者您需要将package_name文件夹添加到sys.path ,然后按照您的尝试import * from a

adding to sys.path could be done with :添加到 sys.path 可以通过以下方式完成:

import sys
module_path = "the path to your package_name"
sys.path.insert(0, module_path)

from ..package_name.lambda_function.a import *

您尝试的操作不起作用,因为您要访问的文件位于不同的目录中。

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

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