为什么在加载模块时使用Paramiko挂起? [英] Why does Paramiko hang if you use it while loading a module?

查看:145
本文介绍了为什么在加载模块时使用Paramiko挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下内容放入文件 hello.py (如果没有,则输入easy_install paramiko):

Put the following into a file hello.py (and easy_install paramiko if you haven't got it):

hostname,username,password='fill','these','in'
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(hostname=hostname, username=username, password=password)
i,o,e = c.exec_command('ls /')
print(o.read())
c.close()

适当地填充第一行.

现在输入

python hello.py

,您将看到一些ls输出.

and you'll see some ls output.

现在输入

python

,然后从解释器类型中输入

and then from within the interpreter type

import hello

瞧!挂了!如果将代码包装在函数foo中并改为执行import hello; hello.foo(),它将解开.

and voila! It hangs! It will unhang if you wrap the code in a function foo and do import hello; hello.foo() instead.

在模块初始化中使用Paramiko为什么会挂起? Paramiko怎么知道它最初是在模块初始化期间使用的?

Why does Paramiko hang when used within module initialization? How is Paramiko even aware that it's being used during module initialization in the first place?

推荐答案

Paramiko对基础传输使用单独的线程. 您应该从不有一个模块,该模块会生成线程作为导入的副作用.据我了解,这里只有一个导入锁,因此当模块中的子线程尝试另一次导入时,它可能会无限期地阻塞,因为您的主线程仍然持有该锁. (可能还有其他我也不知道的陷阱)

Paramiko uses separate threads for the underlying transport. You should never have a module that spawns a thread as a side effect of importing. As I understand it, there is a single import lock available, so when a child thread from your module attempts another import, it can block indefinitely, because your main thread still holds the lock. (There are probably other gotchas that I'm not aware of too)

通常,模块在导入时不应有任何副作用,否则您将获得不可预测的结果.只需使用__name__ == '__main__'技巧暂停执行,就可以了.

In general, modules shouldn't have side effects of any sort when importing, or you're going to get unpredictable results. Just hold off execution with the __name__ == '__main__' trick, and you'll be fine.

我似乎无法创建一个简单的测试用例来重现此僵局.我仍然认为这是import的线程问题,因为auth代码正在等待永远不会触发的事件.这可能是paramiko或python中的错误,但是好消息是,如果做正确的事,就永远不要看到它;)

I can't seem to create a simple test case that reproduces this deadlock. I still assume it's a threading issue with import, because the auth code is waiting for an event that never fires. This may be a bug in paramiko, or python, but the good news is that you shouldn't ever see it if you do things correctly ;)

这是一个很好的例子,为什么您总是要尽量减少副作用,以及为什么函数式编程技术变得越来越普遍.

This is a good example why you always want to minimize side effects, and why functional programming techniques are becoming more prevalent.

这篇关于为什么在加载模块时使用Paramiko挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆