Import with files names conflict

╄→гoц情女王★ 提交于 2021-02-08 07:39:39

问题


I'm trying to develop a simulation class that replaces serial at specific apps(Win7, python 2.7).

I have a SerialHandle class that works in number of apps, It's job is add logic to the well known serial methods, the idea was to replace python serial.py with a dummy file with the same name so we won't have to change and imports at SerialHandle.

Now i have this file with Serial class just like the origin and it works fine:

serial.py
...Serial()

Since i want to really simulate the methods i need the SerialException from serialutil so inside my serial.py i'm trying to import it using:

from serial import SerialException

But as expected i'll get this raise since from serial goes to the local file at first:

Traceback (most recent call last):
  File "C:/CROW/ATE/DUTDrivers/DD_SimulatorExample/DD_SimulatorExample.py", line 18, in <module>
    from Utilities.Serial.SerialHandle.trunk.SerialHandle import SerialHandle
  File "C:\CROW\ATE\Utilities\Serial\SerialHandle\trunk\__init__.py", line 4, in <module>
    from Utilities.Simulator import serial
  File "C:\CROW\ATE\Utilities\Simulator\serial.py", line 11, in <module>
    from serial import SerialException
ImportError: cannot import name SerialException

I understand the problem is the file name since at any other file it will work...

I've tried sys.append(site-packages....serial.py) no luck.

Questions:

  1. Any way to tell the interpreter to ignore the local file at a specific from..import?

  2. Is there any other way to import from an absolute path?

Notes:

  1. the file naming as serial.py is not a decision it's a definition so changing the name is not relevant...

  2. Overloading python serial is not an option also...


回答1:


You must be using python 2.x, since absolute imports are the default in python 3.x. You can use absolute imports in your serial.py file by adding this at the top of the file:

from __future__ import absolute_import

Note that you will need to convert any implicit relative imports from your serial.py file into explicit relative imports. So if you were importing some_func from other_file.py, which is in the same directory, you would need to change that to:

from .other_file import some_func

Note that the "." indicates a relative import from the same package as the current file. See here for additional detail.



来源:https://stackoverflow.com/questions/20998275/import-with-files-names-conflict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!