简体   繁体   English

从其他文件夹python导入模块(错误)

[英]import module from other folder python (errors)

I am new to Python. 我是Python的新手。 I am using the following directory structure and am trying to import module OrgRepo into Func1. 我正在使用以下目录结构,并尝试将模块OrgRepo导入Func1。 I am using a virtualenv and vs code as my IDE. 我正在使用virtualenv和vs代码作为我的IDE。

src/ ├── Functions │ ├── Func1 │ └── Func2 └── Shared ├── __init__.py ├── Repositories │ ├── __init__.py │ ├── OrgRepo └── Utilities ├── __init__.py └── DictUtil I have also tried this without ` init .py' src/ ├── Functions │ ├── Func1 │ └── Func2 └── Shared ├── __init__.py ├── Repositories │ ├── __init__.py │ ├── OrgRepo └── Utilities ├── __init__.py └── DictUtil我也尝试了不使用“ init .py”

This is my PATH: 这是我的路径:

['/Users/username/Documents/Projects/myproject/name/src/Functions/Func1', '/Users/username/anaconda3/envs/my_virtual_env/lib/python37.zip', '/Users/username/anaconda3/envs/my_virtual_env/lib/python3.7', '/Users/username/anaconda3/envs/my_virtual_env/lib/python3.7/lib-dynload', '/Users/username/.local/lib/python3.7/site-packages', '/Users/username/anaconda3/envs/my_virtual_env/lib/python3.7/site-packages']

I have tried the following in order to import OrgRepo into Func1: 为了将OrgRepo导入Func1,我尝试了以下方法:

1: from .Shared.Repositories import OrgRepo 1: from .Shared.Repositories import OrgRepo

ModuleNotFoundError: No module named '__main__.Shared'; '__main__' is not a package

2: from ..Shared.Repositories import OrgRepo ' 2: from ..Shared.Repositories import OrgRepo '

ValueError: attempted relative import beyond top-level package

3: from src.Shared.Repositories import OrgRepo 3: from src.Shared.Repositories import OrgRepo

ModuleNotFoundError: No module named 'src'

4: `from Shared.Repositories import OrgRepo1 4:`从Shared.Repositories导入OrgRepo1

'ModuleNotFoundError: No module named 'Shared'

5: I am using VS Code and when I try to save the file: 5:我使用的是VS Code,当我尝试保存文件时:

It automatically changes to this: import OrgRepo import DictionaryUtilities import datetime import json import sys sys.path.insert(0, 'src/Repositories/') 它会自动更改为: import OrgRepo import DictionaryUtilities import datetime import json import sys sys.path.insert(0, 'src/Repositories/')

6: import sys sys.path.insert( 0, '/Users/username/Documents/Projects/project/m/src/Repositories') import OrgRepo 6: import sys sys.path.insert( 0, '/Users/username/Documents/Projects/project/m/src/Repositories') import OrgRepo

and this: 和这个:

sys.path.insert(0, 'Repositories') sys.path.insert(0, .'Repositories') sys.path.insert(0, ..'Repositories') sys.path.insert(0, 'Repositories') sys.path.insert(0, .'Repositories') sys.path.insert(0, ..'Repositories')

Upon running or saving, vs code changes it to this: import OrgRepo import sys sys.path.insert( 0, '/Users/username/Documents/Projects/project/m/src/Repositories') and received this error: 运行或保存后,vs代码将其更改为: import OrgRepo import sys sys.path.insert( 0, '/Users/username/Documents/Projects/project/m/src/Repositories')并收到此错误:

ModuleNotFoundError: No module named 'OrgRepo'

I was able to install this with PIP and import it, but that does not suit our needs. 我可以通过PIP安装并导入它,但这不符合我们的需求。

I have read these posts: Importing files from different folder 我已阅读以下文章: 从其他文件夹导入文件

Python import modules, folder structures Python导入模块,文件夹结构

How to Import Multiple Python Modules from Other Directories 如何从其他目录导入多个Python模块

How to properly import python modules from an adjacent folder? 如何从相邻文件夹中正确导入python模块?

I tried to read/understand a few other posts as well . 我也尝试阅读/理解其他一些文章。 . . I even tried to bang on the Flux Capacitor a few times to no avail . 我什至试图几次敲打助焊剂电容器都无济于事。 .

EDIT: I am using this code to upload as an AWS Lambda function. 编辑:我正在使用此代码上传为AWS Lambda函数。 While the sys.path solution works locally it makes it does not fit into my workflow. 尽管sys.path解决方案在本地工作,但它不适合我的工作流程。 This requires me to change the sys.path to import while uploading and causes problems with Intellisense. 这需要我在上载时更改要导入的sys.path,并导致Intellisense问题。 I would like to be able to be able to import the module directly. 我希望能够直接导入模块。 eg import OrgRepo so Intellisense does not throw errors and I can zip and upload my package to AWS. 例如, import OrgRepo以便Intellisense不会引发错误,我可以压缩并将程序包上传到AWS。 I have no problem uploading my package to AWS when I am able to import <module_name> . 当我能够导入<module_name>时,我将程序包上传到AWS没问题。

I activate my environment in Anaconda and then export the following PYTHONPATH environment variable: 我在Anaconda中激活我的环境,然后导出以下PYTHONPATH环境变量:

export PYTHONPATH=src/shared/repositories:src/shared/utilities

I also tried export PYTHONPATH=$PATH:src/shared/repositories:src/shared/utilities 我也尝试export PYTHONPATH=$PATH:src/shared/repositories:src/shared/utilities

This worked for a period of time and now I am getting PYTHON[unresolved-import] with IntelliSense. 这工作了一段时间,现在我有了IntelliSense的PYTHON[unresolved-import] I do not appear to get this error when I try to run the script from the directory above /src . 尝试从/src上方的目录运行脚本时,似乎没有收到此错误。

I would be so grateful if somebody can show me how I can import my modules using the standard import <module> and have it consistently work. 如果有人可以向我展示如何使用标准import <module>并使其始终如一地工作,我将不胜感激。

Basically to mention a directory cannot be imported but a file in the directory can be imported. 基本上说不能导入目录,但是可以导入目录中的文件。

Let's say you have Org.py file in OrgRepo and you can do : 假设您在OrgRepo中有Org.py文件,您可以执行以下操作:

from src.Shared.Repositories.OrgRepo import Org

or if you want to call a specific method from it lets say do_it : 或者,如果您要从中调用特定方法,请说do_it

from src.Shared.Repositories.OrgRepo.Org import do_it

Read more 阅读更多

I think what you're trying to do is something like the below. 我认为您要尝试执行的操作类似于以下内容。 I've cleaned up some of the directory names (typically directories are lowercase with underscores and Class names are uppercased), added .py extensions to the python files, and tried to create a minimalistic environment to replicate your scenario. 我已经清理了一些目录名称(通常目录是小写的,带下划线,而类名是大写的),在python文件中添加了.py扩展名,并尝试创建一个简约的环境来复制您的方案。 Hopefully this is helpful. 希望这会有所帮助。

Setup the environment 设置环境

$ mkdir src; mkdir src/functions; touch src/functions/func1.py; mkdir src/shared; mkdir src/shared/repositories; touch src/shared/repositories/org_repo.py

$ tree
.
└── src
    ├── functions
    │   └── func1.py
    └── shared
        └── repositories
            └── org_repo.py

# src/shared/repositories/org_repo.py
def a_cool_func():
    print(f'hello from {__file__}')

# src/functions/func1.py
import pathlib
import sys

file_path = pathlib.Path(__file__)
path = file_path.resolve().parents[2]
sys.path.append(str(path))

from src.shared.repositories.org_repo import a_cool_func

print(f'hello from {__file__}')

a_cool_func()

Run it 运行

# note that there is no significance to /Users/username/tmp/tmp/
# this is just the directory where the test environment was setup
$ python src/functions/func1.py
hello from src/functions/func1.py
hello from /Users/username/tmp/tmp/src/shared/repositories/org_repo.py

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

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