[英]Python cannot properly import from another folder
I am trying to set up a python project from multiple directories to keep it clean. 我正在尝试从多个目录中建立一个python项目以保持其清洁。 I have a parent folder project , and two sub-directories project/sub1 and project/sub2 . 我有一个父文件夹project和两个子目录project / sub1和project / sub2 。
In the sub1 folder, there is a file named Thing.py that is shown below. 在sub1文件夹中,有一个名为Thing.py的文件,如下所示。 All that is in there is a class to hold some variables. 里面所有的东西都有一个可以容纳一些变量的类。 I have also tried no class, just globals in the file. 我也没有尝试过任何课程,只是尝试了文件中的全局变量。 Both result in the same issue. 两者都导致相同的问题。
In the sub2 folder, there is a file that tries to import the class Thing
from Thing.py . 在sub2文件夹中,有一个文件试图从Thing.py导入class Thing
。 It seems importing is not an issue, but Thing
has no attributes after it is imported, so I can't use anything from it. 似乎导入不是问题,但是Thing
在导入后没有属性,因此我无法使用其中的任何内容。
I've tried looking up importing from other folders (with using the sys
module, sys.path.append(import path))
, and also things about __init__.py files, but I cannot get this to work. 我尝试查找从其他文件夹中的导入(使用sys
模块, sys.path.append(import path))
,以及有关__init__.py文件的信息,但是我无法使其正常工作。
Also, if I copy the file to the sub2 folder, it imports fine. 另外,如果我将文件复制到sub2文件夹,则可以正常导入。 The print(dir())
function call prints some things, but nothing I made. print(dir())
函数调用可以打印一些内容,但是我什么也没做。 Help would be appreciated. 帮助将不胜感激。
Thanks. 谢谢。
project/sub1/Thing.py project / sub1 / Thing.py
class Thing:
a = 1
b = 2
project/sub2/Importing File project / sub2 /导入文件
import sys
import tkinter as tk
from tkinter import ttk
sys.path.append(r"..\sub1")
import Thing
print(dir(Thing))
print(dir()) output print(dir())输出
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__path__', '__spec__']
I have added init .py to the project dir as well as to both the subdirectories. 我已经将init .py添加到项目目录以及两个子目录中。 I am using a mac machine so my paths are different you can change them appropriately as you are using a windows machine (I guess). 我使用的是Mac机器,因此我的路径不同,您可以像使用Windows机器一样适当地更改它们(我想)。 I am running the importingfile.py file from sub2 dir (screenshot here) . 我正在从sub2 dir中运行importingfile.py文件(此处是屏幕截图) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.