pythonpython-asyncioparamiko

I am trying to call an async function from a sync callback function (Paramiko Upload Callback) but it fails


import os
import paramiko
import asyncio

async def async_websocket_call(msg):
    print(msg)

async def test_paramiko():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect("web.demo.net", username="root", key_filename=os.environ['USERPROFILE'] + "\\.ssh\\id_rsa")

    def upload_callback(sofar, total):
        loop = asyncio.get_running_loop()
        task = loop.create_task(async_websocket_call("Uploaded: {0:.1f}%".format(100*(sofar/total))))
        asyncio.wait(task, timeout=None)
        
    sftp = ssh.open_sftp()
    sftp.put('test.tar.gz', '/var/www/html/test.tar.gz', upload_callback)
    sftp.close()

    ssh.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(test_paramiko())
loop.close()

I get the error message: RuntimeWarning: coroutine 'wait' was never awaited

Well I can't await the wait method because I am not in an async method...

Update:

asyncssh also does NOT seem to be a solution because

asyncssh sftp.put uses a progress_handler of type SFTPProgressHandler:

SFTPProgressHandler = Optional[Callable[[bytes, bytes, int, int], None]]

So this also does NOT support async callbacks it seems.


Solution

  • So after further digging into this the only solution seems to be:

    import nest_asyncio
    nest_asyncio.apply()
    

    and

    loop = asyncio.new_event_loop()
    loop.run_until_complete