pyserial / pyserial

Python serial port access library
Other
3.21k stars 1.12k forks source link

Support protocol handlers in miniterm #292

Open jamessynge opened 6 years ago

jamessynge commented 6 years ago

I'd like to test my protocol handler using miniterm. For example:

miniterm.py my_scheme:// 9600

This fails because the code needs to add the appropriate package to serial.protocol_handler_packages. So, it would be great to add the required package via command line; for example:

miniterm.py --pkg=my.handlers.package my_scheme:// 9600

zsquareplusc commented 6 years ago

wouldn't it work to set PYTHONPATH?

jamessynge commented 6 years ago

It doesn't work properly, IIUC, if the handler is in a non-top-level package (i.e. the parent directory of the handler is also a package). In particular, if the handler needs to perform imports of other packages in its source tree (e.g. import my.handlers.sibling or import ..sibling), this would require that PYTHONPATH have two directories in it, the root of the source tree and the parent of the such as:

And, again IIUC, this means that sys.modules can easily end up with two imports of the same package but at different paths. Do you concur?

jamessynge commented 6 years ago

I held off on this because I had offered PR #295, but since that is rejected (for what seems to be a good reason), I today tried to use a serial handler by adding its directory to PYTHONPATH, but this doesn't work because only packages in serial.protocol_handler_packages are searched:

protocol_handler_packages = [
    'serial.urlhandler',
]
...
        # if it is an URL, try to import the handler module from the list of possible packages
        if '://' in url_lowercase:
            protocol = url_lowercase.split('://', 1)[0]
            module_name = '.protocol_{}'.format(protocol)
            for package_name in protocol_handler_packages:
                try:
                    importlib.import_module(package_name)
                    handler_module = importlib.import_module(module_name, package_name)

So, would you consider a PR that adds a command line option for adding a package to serial.protocol_handler_packages?