Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何确保Python线程在其目标函数完成后死亡?_Python_Fabric_Paramiko_Python Multithreading - Fatal编程技术网

如何确保Python线程在其目标函数完成后死亡?

如何确保Python线程在其目标函数完成后死亡?,python,fabric,paramiko,python-multithreading,Python,Fabric,Paramiko,Python Multithreading,我有一个产生线程的服务 线程是通过提供目标函数来启动的 当函数结束时,线程似乎没有“死亡”。我之所以知道这一点,是因为线程通过(via)进行了一些SSH连接,如果我执行lsof操作,我会看到SSH连接在函数完成后仍然处于活动状态。 如何确保线程在其目标函数完成时死亡 以下是我正在使用的示例: from time import sleep from threading import Thread from fabric.api import run, settings def thread_fu

我有一个产生线程的服务
线程是通过提供目标函数来启动的
当函数结束时,线程似乎没有“死亡”。我之所以知道这一点,是因为线程通过(via)进行了一些SSH连接,如果我执行
lsof
操作,我会看到SSH连接在函数完成后仍然处于活动状态。
如何确保线程在其目标函数完成时死亡

以下是我正在使用的示例:

from time import sleep
from threading import Thread
from fabric.api import run, settings

def thread_func(host):
    with settings(host_string=host):
        run('ls -lht /tmp')

def spawn_thread(host):
    t = Thread(
        target=thread_func,
        args=(host,)
    )
    t.start()

spawn_thread('node1.example.com')
while True:
    sleep(1)
如果我在另一个终端上运行
sudo lsof | grep ssh
,而上面的代码处于无限循环中,即使我知道线程不应该再存在,我也会看到以下内容:

python    6924      daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924      daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)
python    6924 6930 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924 6930 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)
python    6924 6932 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924 6932 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)

您确定您的结构模块仅在ls命令期间执行ssh吗。也就是说,它应该做的相当于

ssh主机ls-lht/tmp

此命令行将打开远程shell以运行ls-lht命令,然后关闭

但我怀疑Fabric库可能在做类似的事情:

ssh主机

主机$ls-lht/tmp .


当然,它没有提供真正的tty,但是有不同的ssh选项,允许在没有交互式tty的情况下保持连接打开。这在某些情况下是可取的(例如,如果在同一台主机上运行许多命令,此技术将重用现有ssh会话,而不是每次打开新会话。请查看文档中的参数以启用或禁用此类会话缓存。

线程功能是否实际完成?如果在with:run()之前和之后放置print语句block,您看到run()实际返回了吗?您是对的,Fabric不会为每个命令创建新会话。会话是缓存的。不过,我希望线程函数完成后会关闭所有会话。