如何防止python解释器查看和导入未安装的模块;不属于该系统?

时间:2016-04-11 18:00:14

标签: python oop raspberry-pi beagleboneblack

问题的简短版本:

如何阻止python解释器查看和导入未安装的模块;不属于我使用的系统;如果我选择在System X而不是System Y下运行代码,则不需要?

从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

我想避免为不同的主板创建不同的项目。我知道怎么做。

长版

我正在尝试在我的项目中实现一个接口,以便与德州的ADC IC进行通信。 最终目标是能够从几个不同的设备读取它:

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

为此,我创建了一个接收读取器对象的接口,该读取器对象继承自抽象读取器类。

我想避免为不同的主板创建不同的项目。我知道怎么做。

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

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***

2 个答案:

答案 0 :(得分:1)

使用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***

答案 1 :(得分:1)

How to check if a python module exists without importing it

您也可以使用os.name来检测设备类型。