with ssh() pt3.5: Clarifying a little
Earlier I posted the current implementation of ayrton
's with ssh()
. I did a
mistake in the examples of the resulting code, and there was no explicit example,
so this post is mostly to clarify that:
with ssh ('localhost', allow_agent=False, password='foobarbaz') as s: foo= input () print ('yes!', foo) print ('I said yes!') (i, o, e)= s i.write (b'no! maybe!\n') print (o.readlines ()) print (e.readlines ())
ayrton
's code will rewrite this to something equivalent to this:
with ssh (pickle.dumps (<module>))), 'localhost', allow_agent=False, password='foobarbaz') as <random_var>: s= <random_var> (i, o, e)= s i.write (b'no! maybe!\n') print (o.readlines ()) print (e.readlines ())
where <module>
is built by creating an ast.Module
who's body is the with
's body;
and <random_var>
is a name randomly generated (it's a sequence of 4 groups of
a lowercase letter and an digit; for instance, j6r3t8y9
).
The execution of said program gives the following:
[b'yes! no! maybe!\n', b'I said yes!\n'] []
But trying to explain why we need the s= <random_var>
step, I noticed that
actually we don't: according to
Python's documentation,
the only things that are blocks who define binding scopes are modules, classes and
functions/methods. This means that names binded as the target of a with
statement outlives the body of said with
statement. This puts us back to the
simpler situation where we just replaced the with
's body with pass
.
So, finally, our previous example ends up like:
with ssh (pickle.dumps (<module>))), 'localhost', allow_agent=False, password='foobarbaz') as s: pass (i, o, e)= s i.write (b'no! maybe!\n') print (o.readlines ()) print (e.readlines ())
and works all the same :)