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

查看:18
本文介绍了为什么在加载模块时使用 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

然后从解释器类型中

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.

我似乎无法创建一个简单的测试用例来重现这个死锁.我仍然认为这是导入的线程问题,因为身份验证代码正在等待一个永远不会触发的事件.这可能是 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天全站免登陆