TypeError: A Future or coroutine is required

2024/10/17 19:49:09

I try make auto-reconnecting ssh client on asyncssh. (SshConnectManager must stay in background and make ssh sessions when need)

class SshConnectManager(object):
def __init__(self, host, username, password, port=22):self._host = hostself._username = usernameself._password = passwordself._port = portself.conn = Noneasyncio.async(self.start_connection)@asyncio.coroutine
def start_connection(self):try:Client = self._create_ssh_client()self.conn, _ = yield from asyncssh.create_connection(Client,self._host, port=self._port,username=self._username,password=self._password)except Exception as e:print("Connection error! {}".format(e))asyncio.async(self.start_connection())def _create_ssh_client(self):class MySSHClient(asyncssh.SSHClient):parent = selfdef connection_lost(self, exc):self.parent._handle_connection_lost(exc)return MySSHClientdef _handle_connection_lost(self, exc):print('Connection lost on {}'.format(self.host))print(exc)asyncio.async(self.start_connection)ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)asyncio.get_event_loop().run_until_complete(...)

Please do not look at _create_ssh_client or other "haks"

Problem is:

$ python3 main.py 
Traceback (most recent call last):File "main.py", line 75, in <module>ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)File "main.py", line 22, in __init__asyncio.async(self.start_connection)File "/usr/lib/python3.4/asyncio/tasks.py", line 565, in asyncraise TypeError('A Future or coroutine is required')
TypeError: A Future or coroutine is required

But self.start_connection is corutine! Or not? Or what is another way start async task from sync code?

Answer

Thanks @dano and @boardrider for help in comments. Bug was what @asyncio.coroutine return function what need to call to get generator object. I forget to do this.

Fixed version:

class SshConnectManager(object):
def __init__(self, host, username, password, port=22):self._host = hostself._username = usernameself._password = passwordself._port = portself.conn = None# FIX HEREasyncio.async(self.start_connection())@asyncio.coroutine
def start_connection(self):try:Client = self._create_ssh_client()self.conn, _ = yield from asyncssh.create_connection(Client,self._host, port=self._port,username=self._username,password=self._password)except Exception as e:print("Connection error! {}".format(e))asyncio.async(self.start_connection())def _create_ssh_client(self):class MySSHClient(asyncssh.SSHClient):parent = selfdef connection_lost(self, exc):self.parent._handle_connection_lost(exc)return MySSHClientdef _handle_connection_lost(self, exc):print('Connection lost on {}'.format(self.host))print(exc)# AND HEREasyncio.async(self.start_connection())ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)asyncio.get_event_loop().run_until_complete(...)

P.S. But i don't undestood why coroutine decorator can't return called decorator. (This make me confuse, i confuse this with twisted callbacks).

And i found how to remember this, have simple case, if start_connection can get arguments:

@asyncio.coroutine
def start_connection(self, some_arg):pass

so, i can simple write:

asyncio.async(self.start_connection(some_val))

and not need to make additional attributes in asyncio.async function

https://en.xdnf.cn/q/72913.html

Related Q&A

Python socket closed before all data have been consumed by remote

I am writing a Python module which is communicating with a go program through unix sockets. The client (the python module) write data to the socket and the server consume them.# Simplified version of t…

Python child process silently crashes when issuing an HTTP request

Im running into an issue when combining multiprocessing, requests (or urllib2) and nltk. Here is a very simple code:>>> from multiprocessing import Process >>> import requests >>…

Shared variable in concurrent.futures.ProcessPoolExecutor() python

I want to use parallel to update global variable using module concurrent.futures in pythonIt turned out that using ThreadPoolExecutor can update my global variable but the CPU did not use all their pot…

MongoEngine - Another user is already authenticated to this database. You must logout first

Can anyone please explain why I am getting error Another user is already authenticated to this database. You must logout first when connecting to MongoDB using Flask MongoEngine?from mongoengine.conne…

How to bucketize a group of columns in pyspark?

I am trying to bucketize columns that contain the word "road" in a 5k dataset. And create a new dataframe. I am not sure how to do that, here is what I have tried far : from pyspark.ml.featur…

Dictionary of tags in declarative SQLAlchemy?

I am working on a quite large code base that has been implemented using sqlalchemy.ext.declarative, and I need to add a dict-like property to one of the classes. What I need is the same as in this ques…

How to connect to a GObject signal in python, without it keeping a reference to the connecter?

The problem is basically this, in pythons gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:class ClipboardMonitor (object):def __init__(self):clip = gtk.clipboar…

openpyxl please do not assume text as a number when importing

There are numerous questions about how to stop Excel from interpreting text as a number, or how to output number formats with openpyxl, but I havent seen any solutions to this problem:I have an Excel s…

NLTK CoreNLPDependencyParser: Failed to establish connection

Im trying to use the Stanford Parser through NLTK, following the example here.I follow the first two lines of the example (with the necessary import)from nltk.parse.corenlp import CoreNLPDependencyPars…

How to convert hex string to color image in python?

im new in programming so i have some question about converting string to color image.i have one data , it consists of Hex String, like a fff2f3..... i want to convert this file to png like this.i can c…