Socco Socco - 24 days ago 6
Python Question

Why is serial.tools available within os.system but not without?

I am working up to getting Python to read from a microcontroller which sends a short status string every second over COM port.

As the μC (better not say which) has a fairly dodgy serial over USB implementation, I need to regularly check if the COM port exists.

I can use

os.system('python -m serial.tools.list_ports')
to return the ports in Eclipse's Console. All good so far.

I now want to go the next step and pass its output into a variable and process further - this is where I get unstuck. I would have thought I could assign using eg:
s = serial.tools.list_ports
but
tools
is not available within
serial
in this context.

Why is this?

Answer

If you're only importing serial, you can't access serial.tools directly because tools is another module (actually, a sub-package) within the serial package. The serial package doesn't import it for you. Some packages automatically import some or all of the modules and subpackages they contain, but that behavior needs to be specifically coded by the package developers, it's not done by Python unless you import the inner module yourself.

Try explicitly importing the module you want to use:

import serial.tools.list_ports
serial.tools.list_ports.main()

The main function implements the behavior you see when you run python -m serial.tools.list_ports. I found its name by looking in the PySerial subversion repository on Sourceforge.