简体   繁体   English

Python3导入问题

[英]Python3 Imports Issue

So... I am attempting to teach myself Python. 所以...我试图自学Python。

In such, I am attempting to build something that I appear to have no clue about... 这样,我正在尝试构建一些我似乎毫无头绪的东西。

I have a "workingdir" structure such as: 我有一个“ workingdir”结构,例如:

/
-- classes/
-- -- install
-- myfile

In myfile I am simply attempting to "import" the file install by using: import classes.install myfile我只是尝试使用以下方式“导入”文件installimport classes.install

Which fails with: ImportError: No module named 'classes.install' 失败的原因: ImportError: No module named 'classes.install'

I have attempted the following as well, and all end the same way, with the same error: 我也尝试了以下操作,并且都以相同的方式结束了,但出现了相同的错误:

import .classes.install

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import classes.install

As well as putting an empty __init__.py file inside the classes directory 以及将一个空的__init__.py文件放入classes目录中

the file install simply contains: 该文件install仅包含:

class gyo_install():

    inst = False

    # check if we have everything we need installed.
    def __init__():
        print("Hello World")

What am I doing wrong? 我究竟做错了什么? I've searched and searched and searched, everything I see points to the same solutions I've attempted, and none of them work. 我已经搜索,搜索和搜索了,我看到的所有内容都指向我尝试过的相同解决方案,但是它们都不起作用。

Python looks for files with a .py extension when importing modules. 导入模块时,Python查找扩展名为.py的文件。 So a file named myfile will not be recognized simply by the command import myfile . 因此,名为import myfile的命令不会简单地识别名为myfile的import myfile The pythonic way to ensure that the interpreter will find the module is to ensure it has a .py extension. 确保解释器将找到模块的pythonic方法是确保其扩展名为.py。 Renaming myfile to myfile.py and install to install.py and then changing the import command to 将myfile重命名为myfile.py并安装到install.py,然后将import命令更改为

import classes.install

should solve the problem. 应该解决问题。

Create __init__.py inside install directory. 在安装目录中创建__init__.py

Explanation: You can import from a file that is in your current directory or from a package. 说明:您可以从当前目录中的文件或包中导入。 A package is a directory with __init__.py inside. 包是一个内部带有__init__.py的目录。 In fact, a package can contain only this single file. 实际上,一个软件包只能包含一个文件。

You can read the documentation for further information. 您可以阅读文档以获取更多信息。

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

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