简体   繁体   English

如何解决:尝试在没有已知父 package 的情况下进行相对导入

[英]How to solve: attempted relative import with no known parent package

I have a project structure with mostly empty python files:我有一个项目结构,其中大部分是空的 python 文件:

-project
  --work1
      --__init__.py
      --app.py
      --momo.py

momo.py莫莫.py

import numpy as np
def plus(x):
    return x

app.py应用程序.py

from . import momo
a = momo.plus(6)

Running app.py directly results in this error:直接运行 app.py 会导致这个错误:

from . import momo
ImportError: attempted relative import with no known parent package

I have tried change to "from plus import momo" but this yields the same error.我尝试更改为“from plus import momo”,但这会产生相同的错误。

Python version 3.8 Python 3.8版

Any hints would be much appreciated.任何提示将不胜感激。

You shouldn't import like you said.你不应该像你说的那样导入。

you can just try this:你可以试试这个:

import momo

it should add momo to your current file.它应该将momo添加到您当前的文件中。

and for using functions which has been declared in momo , you should call the function name after momo.对于使用已经在momo中声明的函数,您应该在 momo 之后调用 function 名称momo. . . for example:例如:

a = momo.plus(12)

if you just want to import plus`` from momo``` file, you can try如果你只是想plus`` from ,你可以试试

from momo import plus

then you just need to call function name, instead of the whole file and functions together.那么您只需要调用 function 名称,而不是将整个文件和函数一起调用。 eg:例如:

a = plus(12)

Try running it from project directory as module (-m flag):尝试从project目录作为模块运行它(-m 标志):

$ cd project
$ python -m work1.app 

because when you're starting app directly like python app.py , is doesn't know that current folder is actually a package with __init__.py but dot in from. import *因为当你像python app.py一样直接启动应用程序时,不知道当前文件夹实际上是一个 package 带有__init__.py但点 in from. import * from. import * is a shortcut for a current package. from. import *是当前 package 的快捷方式。

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

相关问题 如何解决 python 中的“在没有已知父包的情况下尝试相对导入”错误 - How to solve "attempted relative import with no known parent package" error in python 如何使用这个简单的包避免“在没有已知父包的情况下尝试相对导入”? - How to avoid "Attempted relative import with no known parent package" with this simple package? Python - 尝试在没有已知父包的情况下进行相对导入 - Python - attempted relative import with no known parent package 导入错误:尝试在没有已知父包的情况下进行相对导入? - ImportError: attempted relative import with no known parent package? Python 尝试在没有已知父 package 的情况下进行相对导入 - Python attempted relative import with no known parent package ImportError:尝试在没有已知父 package 的情况下进行相对导入:( - ImportError: attempted relative import with no known parent package :( 尝试在没有已知父项的情况下进行相对导入 package (python) - attempted relative import with no known parent package (python) ImportError:尝试相对导入,没有已知的父包 - ImportError: attempted relative import with no known parent package 导入错误 - 在没有已知父包的情况下尝试相对导入 - ImportError - attempted relative import with no known parent package “尝试在没有已知父包的情况下进行相对导入” - “Attempted relative import with no known parent package”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM