Py学习  »  Python

不能从Python中同一目录中的另一个文件导入类

user2128702 • 4 年前 • 143 次点击  

我对巨蟒还很陌生,而且我还在适应它。我有一个项目,它是通过使用一组只包含函数定义的文件编写的。我决定在OOP范式中重新构建它,所以这就是发生的事情:

当时,我有两个文件:

Main
 | ---- loggingManager.py
 | ---- servoManager.py

在servomager.py脚本中,我有:

from loggingManager import *
...
from time import sleep

一切都很好。我可以使用所有的功能 DEF 在loggingmanager.py中没有任何问题。

现在我有了这样的想法:

Main
 | ---- Logger.py
 | ---- ConfigurationWrapper.py

配置包装器的内容是:

import configparser

class ConfigurationWrapper:
    default_path = '/home/pi/Desktop/Bree/config.ini'

    def __init__(self, path_to_file=None):
        if path_to_file is None:
            path_to_file = self.default_path
...

日志记录程序如下:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwarg$
        else:
            cls._instances[cls].__init__(*args, **kwargs)

        return cls._instances[cls]

class Logger():
    __metaclass__ = Singleton

我的目标是导入:

import ConfigurationWrapper

在logger.py脚本文件中,但每次执行此操作时,都会收到一个错误(通过在MacOS上的终端中键入“python logger”):

Traceback (most recent call last):
  File "Logger", line 1, in <module>
    import ConfigurationWrapper
ImportError: No module named ConfigurationWrapper

我试图在同一个文件夹中添加空的init文件,但仍然没有发生任何事情。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38633
 
143 次点击  
文章 [ 2 ]  |  最新文章 4 年前
user2128702
Reply   •   1 楼
user2128702    5 年前

我的解决方法是增加:

execfile("./ConfigurationWrapper")

但我想知道这有多合适。

Giovanni Dias
Reply   •   2 楼
Giovanni Dias    5 年前

尝试在导入的模块之前添加一个点(.)。

import .ConfigurationWrapper

或者导入你的类

from .ConfigurationWrapper import ConfigurationWrapper

点(.)表示从同一目录导入。