[英]How can I get access to this nonglobal variable in nested functions in Python 2.x?
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. 我想在嵌套函数
run_exec_command_thread
中使stdin
, stdout
和stderr
与它的父函数共享。 I'm using Python 2.7 so I can't use nonlocal
. 我正在使用Python 2.7,所以不能使用
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
. 在这种情况下,我不知道如何在它们之间共享变量,因为在这种情况下,我不知道如何实现dict解决方案,因为对象类型是
paramiko.channel.ChannelFile
。 I'm hoping somebody can get me going in the right direction. 我希望有人能使我朝正确的方向前进。
This isn't really related to nested functions. 这实际上与嵌套函数无关。
It looks like stdin
etc won't be created until the function is run, ie in a new Thread
. 在函数运行之前,即在新的
Thread
,似乎不会创建stdin
等。
This means it should be solvable using a standard variable sharing across Threads approach, eg using a Queue
- see here: How to share a variable between 2 threads 这意味着它应该可以使用跨线程共享的标准变量方法来解决,例如使用
Queue
-参见此处: 如何在2个线程之间共享变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.