简体   繁体   English

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

[英]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.

相关问题 如何使用本地 Python 解释器进行全局 pylint 安装以防止“无法导入”错误? - How do I make a global pylint installation use a local Python interpreter to prevent "Unable to import" errors? 我如何使用已安装的 python 模块 - How do i use installed python modules 如何安装导入numpy、pandas等模块? 我想使用IDLE编辑/运行环境,安装了Python 3.10 - How do I install and import modules such as numpy and pandas? I want to use the IDLE editing/run environment, and I have Python 3.10 installed 如何让python识别安装在虚拟环境中的模块? - how do I get python to recognize modules installed in virtual environment? 如何获取本地安装的 Python 模块的列表? - How do I get a list of locally installed Python modules? 尽管安装在使用过的 python 解释器中,但无法在 pycharm 中导入模块 - Unable to import modules in pycharm in spite being installed in the used python interpreter 如何通过Python解释器Chrome应用程序在webports / naclports中使用Python模块? - How do I use the Python modules in webports/naclports with the Python interpreter Chrome app? 如何创建自定义 python 解释器? 即某些模块已经包括在内? - How do I create a custom python interpreter? i.e. with certain modules already included? 我的SDK有自己的python解释器。 如何为其安装模块? - My SDK has its own python interpreter. How do I install modules for it? 在vscode中选择python解释器时,如何找到通过wsl2安装的virtualenv路径? - How do I find the virtualenv path installed via wsl2 when choosing python interpreter in vscode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM