Python Forum

Full Version: Get Serial ports via Function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the below code that works fine by itself but not in a function to retrieve the name of the serial ports.

import serial.tools.list_ports
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
    print(port.device)
I want to be able to use the code between windows and linux based systems to pull the current serial ports (active) and populate a combobox for them with their names.

When I put the above code in a function I get an error of : TypeError: _getserial_ports() takes 0 positional arguments but 2 were given

when my checkbox (checkboxsb) is changed it will call the function. The function will currently only print it to the console, i'm just trying to get it to work within a function before tackling adding the items to a combobox.

#!/usr/bin/python3
import os
import sys
import serial.tools.list_ports


from PyQt5 import QtCore, QtGui, QtWidgets, uic

LOCAL_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"


class Main(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = uic.loadUi(LOCAL_DIR + "ooeygui.ui", self)

        self.ui.checkboxsb.stateChanged.connect(self._pullcheckboxsb)
        self.ui.checkboxsb.stateChanged.connect(self._getserial_ports)

        self.show()

    def _getserial_ports():
        
        ports = serial.tools.list_ports.comports(include_links=False)
        for port in ports :
            print(port.device)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    gui = Main()
    sys.exit(app.exec_())

i found my issue with my code. i forgot to put in the 'self' within the def_getserial_ports function...
Since you already use Qt framework it would require less dependancies to use their serial port interface as well (full example here):

#!/usr/bin/python3
import sys
from PyQt5 import QtCore, QtWidgets, QtSerialPort


def ports():
    availables = []
    for port in QtSerialPort.QSerialPortInfo.availablePorts():
        availables.append(port.systemLocation())
    if availables:
        availables = str(availables)
        return(availables.translate({ord(c): None for c in "[']"}))
    return("none")

if __name__== '__main__':
    app = QtWidgets.QApplication([])
    print(ports())
    sys.exit(app.exec_())