[英]How do I prevent python interpreter to see and import modules that are not installed; do not belong to the system?
Short version of the question: 问题的简短版本:
How do I prevent python interpreter to see and import modules that are not installed; 如何防止python解释器查看和导入未安装的模块; do not belong to the system I am using;
不属于我正在使用的系统; and are not required if I choose to run the code under System X instead of System Y?
如果我选择在系统X而不是系统Y下运行代码,是否不需要?
From a C perspective I would do something on those lines: 从C的角度来看,我会在这些方面做些事情:
#if defined(__SerialCOM__)
// Do stuff, import stuff
#elif defined(__SPI_Over_Raspberry__)
// Do stuff, import stuff
#elif defined(__SPI_Over_BeagleBone__)
// Do stuff, import stuff
#endif
I would like to avoid creating different projects for different boards. 我想避免为不同的董事会创建不同的项目。 This I know how to do.
我知道该怎么办。
Long Version 长版
I am trying to implement in my project an interface to communicate to an ADC IC from texas. 我正在尝试在我的项目中实现一个接口,以与德州的ADC IC通信。 The end goal is to be able to read from it with several different devices:
最终目标是能够使用几种不同的设备从中读取信息:
ADC <---SPIbus (With C code)---> ArduinoDue <-----Serial (With Python)----> LinuxPC
ADC <---SPIbus (With Python)---> Raspberry Pi3
ADC <---SPIbus (With Python)---> BeagleBone Black
ADC <---SPIbus (With Python)---> Intel Edson
For such, I created an interface, that receives a reader object, this reader object inherits from an abstract reader class. 为此,我创建了一个接口,该接口接收一个读取器对象,该读取器对象从抽象读取器类继承。
I would like to avoid creating different projects for different boards. 我想避免为不同的董事会创建不同的项目。 This I know how to do.
我知道该怎么办。
readerhandler.py readerhandler.py
from readers import SerialReader,PiSPIreader
class ReaderHandler:
def __init__(self, readertype="PiSPI"):
self.reader = self.getreader(readertype)
def getreader(self, readertype):
aReader = []
if readertype == "PiSPI":
aReader = PiSPIreader()
elif readertype == "Serial":
aReader = SerialReader()
elif readertype == "BBSPI":
aReader = BBSPIreader()
else:
print("reader type invalid")
return aReader
# Do other stuff
readers.py readers.py
from abc import ABCMeta, abstractmethod
import serial # For Serial Reader object (Should only be interpreted in a pc device)
import piSPI # For piSPI Reader object (Should only be interpreted in a RasberryPi device)
import bbSPI # For bbSPI Reader object (Should only be interpreted in a BeagleBone Black device)
class Reader(object): # My abstract class
__metaclass__ = ABCMeta
@abstractmethod
def initialization(self):
"""Acquisitions setup"""
@abstractmethod
def _run(self):
"""function that acquires sample from device port on the bakcground"""
@abstractmethod
def readdata(self, nofsamples=100):
"""Read X buffered samples"""
class SerialReader(Reader): # (Should only be interpreted in a PC device)
def __init__(self, portname='/dev/ttyACM2', baudrate=115200, magic0=0x42, magic1=0x41):
super(SerialReader, self).__init__()
self.ser = serial.Serial(portname, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
# Implements other abstract methods and **uses Serial object***
class PiSPIreader(Reader): # (Should only be interpreted in a Rasberry device)
def __init__(self):
super(PiSPIreader, self).__init__()
self.piSPI = piSPI.SPI()
# Implements other abstract methods and **uses piSPI object***
class BBSPIreader(Reader): # (Should only be interpreted in a BeagleBone Black device)
def __init__(self):
super(BBSPIreader, self).__init__()
self.bbSPI = bbSPI.SPI()
# Implements other abstract methods and **uses bbSPI object***
Use try/except
. 使用
try/except
。
try:
import serial
except ImportError:
pass # couldn't import serial, so do nothing
else: # we successfully imported serial, so define the class that uses it
class SerialReader(Reader): # (Should only be interpreted in a PC device)
def __init__(self, portname='/dev/ttyACM2', baudrate=115200, magic0=0x42, magic1=0x41):
super(SerialReader, self).__init__()
self.ser = serial.Serial(portname, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
# Implements other abstract methods and **uses Serial object***
How to check if a python module exists without importing it 如何在不导入的情况下检查python模块是否存在
you may also use os.name, for detecting the device kind. 您也可以使用os.name来检测设备种类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.