问题
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:
Any way to tell the interpreter to ignore the local file at a specific from..import?
Is there any other way to import from an absolute path?
Notes:
the file naming as
serial.py
is not a decision it's a definition so changing the name is not relevant...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