I
I
Ilya Ryabykin2019-01-05 00:58:45
Python
Ilya Ryabykin, 2019-01-05 00:58:45

How to complete the subtraction of a generator from another instance of the program?

Hello everybody.
Working with paramiko and channels (web-socket) in Django.
Implemented a class for creating a connection and executing commands on the server via paramiko.Transport.
An instance of this class in this context is executer.
I create an instance of the class - executer, execute a command, the result of which goes to self.session.recv (which I am going to read through the next generator method).
Generator method from the executer class:

def gen(self):
    while not self.session.exit_status_ready():
        yield self.session.recv(self.RECV_BYTES).decode("utf-8") \
              or self.session.recv_stderr(self.RECV_BYTES).decode("utf-8")

I execute the command "tail -f textfile".
I subtract constantly incoming data from the generator (never interrupt) and send the result via web-socket:
An instance of the WebsocketConsumer class:
for message in self.executer.gen:
            self.send(text_data=json.dumps({
                'message': str(message)
            }))

The problem is that this generator will always be waiting, because. self.session.exit_status_ready() will never return True (in the case of "tail -f textfile").
QUESTION:
I am looking for a solution how to complete the subtraction from the generator from outside (for example, via a web socket, by calling some function that will connect to self.session and call the close() method)
Any other thoughts?
Worst:
In the generator, do a subtraction from the base (by some unique key of the command being executed and if there is "done") - complete the execution of the generator.
Cons: a lot of requests to the database; if the executed command does not return anything, yield does not work and we do not look at the database -> completion will not happen either.
Not implemented:
Call the subtract loop from the generator asynchronously via asyncio.Future and terminate execution via close. Using a web socket is also impossible, because. it will be impossible to access the executing context.
etc.
Unfinished:
Save via pickle an instance of the paramiko.Transport object for the command being executed, if necessary, load it and end the session (it was not possible to save the object due to objects with locks) and have not tried it at all, is it possible ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
santaatnas, 2019-01-05
@santaatnas

You need a second thread that will listen to the connection (TCP, HTTP, Web Socket - it doesn't matter) and when accessing it - call close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question