简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM