pythonpython-3.xinspection

Import ftplib in dynamically instanciated member class


Based on this template I want to create my own CLI Interface to manage our services. Basically this CLI skeleton uses inspection to match CLI arguments/commands to a member class in the module 'commands' and instanciate it via .run() method

One of my commands should be 'fetch' which basically downloads some data from an FTP server.

so I have an fetch.py class in my commands module.

When I do from ftplib import FTP now in this dynamically instanciated module member, it fails immediately with an weird TypeError in socket.py in ftplib

So it seems, that ftplib has issues with being imported this way (other libraries like json work perfectly well).


Solution

  • It seems, that ftplib is the only module which has issues being imported in a dynamically loaded module.

    Therefore I dynamically loaded ftplib itself right in the Moment before I Need it to get some files. importlib does me that favor:

    ftplib = importlib.import_module('ftplib')
    

    After that I am able to use ftplib just in the classical way:

    with ftplib.FTP(config['FTP']['Host']) as ftp:
        ftp.login(user=config['FTP']['User'], passwd=config['FTP']['password'])