python3 -m switch files

Viewed 44

If I run this on my (Linux) command line.

python3 -m serial.tools.list_ports

I get the result:

/dev/ttyUSB0        
1 ports found.

What files (or sequence of files) are run by this -m switch?

I have various python directories in my /usr/ directory but no specific serial.py file (I can see serialcli.py & serialutil.py, serialize.py etc) so the command is being 'turned' into some form to use a 'serial based' file, but which one?.

How does it generate the output?

In python code when I use this command no output is generated so I guess the -m switch taps into an output routine??

The output from this command (and other examples) is quite useful and I may want to use it in python itself rather than from BASH.

I am aware it's not meant for this but for testing purposes, but still... ;)

Q: So what files are actually 'tapped into' in this 'serial' example?

1 Answers

The -m flag in python is used for:
-m mod : run library module as a script (terminates option list)

What does "terminates option list" mean? It means that, any future options get passed to the program you are providing and not to python.

So in your scenario, it's running the list_ports module as a script

python3 -m serial.tools.list_ports

How can you use it in python itself?

  1. You can import the serial module and call functions inside list_ports. I am very sure, you have these files in your workspace / environment, because you have installed pyserial
  2. Alternatively - you can also install pyserial in a virtual environment, and run some experiments.

If you "really, really" want to use this like a bash command, within a python script? Do take a look at the subprocess module.

Subprocess

Pyserial - serial.tools.list_ports

Related