0

I've been trying to find a solution and have looked here and here.

Here is my code:

def sshRunCommand(self, command, print_stdout=True, print_stderr=True):

    def run_exec_command_thread(command):
        (stdin, stdout, stderr) = self.client.exec_command(command)

    # Appends command to always change to the home directory first
    x = "cd /home/" + self.username + "/; " + command

    # Locally output an terminal-esque command look-a-like
    if print_stdout:
        print self.username + "@" + self.payloadd + ":" + x

        exec_command_thread = Thread(
            target=run_exec_command_thread,
            args=(x,))
        exec_command_thread.daemon = True
        exec_command_thread.start()

        while exec_command_thread.isAlive():
            a = stdout.readlines()
            for b in a:
                print b

I want to make stdin, stdout, & stderr in the nested function run_exec_command_thread to be shared with it's parent function. I'm using Python 2.7 so I can't use nonlocal. I don't know how to share the variables between them for this specific case because I don't know how to implement a dict solution in this case because the object type is a paramiko.channel.ChannelFile. I'm hoping somebody can get me going in the right direction.

Community
  • 1
  • 1
user3000724
  • 651
  • 3
  • 11
  • 22

1 Answers1

0

This isn't really related to nested functions.

It looks like stdin etc won't be created until the function is run, i.e. in a new Thread.

This means it should be solvable using a standard variable sharing across Threads approach, e.g. using a Queue - see here: How to share a variable between 2 threads

Community
  • 1
  • 1
jmetz
  • 12,144
  • 3
  • 30
  • 41
  • So I'm using Queues already for sharing data between threads, but that exec_command runs and populates a local variable called stdout. I want to get that output in real time because the command takes over 15 minutes to finish (so I don't want to print after it completes). So a solution to this is going to require running the exec_command in a separate thread and consistently read the variable. Any ideas on how to accomplish this? – user3000724 Mar 18 '16 at 15:03