相关疑难解决方法(0)

如何从python中的线程获取返回值?

如何获取foo从线程目标返回的值?

from threading import Thread

def foo(bar):
    print('hello {}'.format(bar))
    return 'foo'

thread = Thread(target=foo, args=('world!',))
thread.start()
return_value = thread.join()
Run Code Online (Sandbox Code Playgroud)

如上所示,"一种显而易见的方法"不起作用:'foo'返回'foo'.

python multithreading

289
推荐指数
15
解决办法
28万
查看次数

在python中并行执行任务

我使用的是python 2.7,我有一些看起来像这样的代码:

task1()
task2()
task3()
dependent1()

task4()
task5()
task6()
dependent2()

dependent3()
Run Code Online (Sandbox Code Playgroud)

这里唯一的依赖关系如下:dependent1需要等待tasks1-3,dependent2需要等待任务4-6,dependent3需要等待dependents1-2 ......以下就可以了:先运行整个6个任务并行,然后前两个家属并行..然后最终依赖

我喜欢尽可能多地并行运行任务,我已经搜索了一些模块,但我希望避免使用外部库,并且不确定Queue-Thread技术如何解决我的问题(也许有人可以推荐一个好资源) ?)

python queue parallel-processing multithreading

24
推荐指数
2
解决办法
4万
查看次数

python中的线程:使用target =时检索返回值

可能重复:
从线程返回值

我想得到像这样的一堆服务器的"免费记忆":

def get_mem(servername):  
    res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)  
    return res.read().strip()  
Run Code Online (Sandbox Code Playgroud)

因为这可以是线程我想做类似的事情:

import threading  
thread1 = threading.Thread(target=get_mem, args=("server01", ))  
thread1.start()
Run Code Online (Sandbox Code Playgroud)

但是现在:如何访问get_mem函数的返回值?我真的需要去一个全功能的方式创建class MemThread(threading.Thread)和覆盖__init____run__

python memory multithreading

14
推荐指数
1
解决办法
2万
查看次数

Python:如何从线程函数中获取多个返回值

调用了一个返回多个值的外部函数。

def get_name(full_name):
   # you code
   return first_name, last_name
Run Code Online (Sandbox Code Playgroud)

在简单的函数调用中,我可以得到结果。

from names import get_name

first, last= get_name(full_name)
Run Code Online (Sandbox Code Playgroud)

但是我需要使用线程进行调用以获取第一个和最后一个变量的结果值。我未能使用简单的线程调用。

first, last= Threading.thread(get_name, args= (full_name,)
Run Code Online (Sandbox Code Playgroud)

请帮我获取函数调用的返回值

python multithreading multiprocessing

7
推荐指数
1
解决办法
9219
查看次数

从线程中生成项目

from threading import Thread
import time
print 'start of script'

class MyThread(Thread):
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def run(self):
        for i in xrange(self.start,self.end):
            yield i




my_threads = []

my_thread = MyThread(1,6)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(6,11)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(11,16)
my_thread.start()
my_threads.append(my_thread)


for t in my_threads:
    print t.join()

print 'end of script'
Run Code Online (Sandbox Code Playgroud)

我怎样才能正确地做到这一点?我正在尝试打印数字:范围(1,16),其中我从在单独线程中运行的函数的输出中获取该数字。

我知道我不会按顺序获得这个数字范围,因为函数的本质是在单独的线程中运行。

我也知道我可以简单地在线程函数本身中打印它们,但这不是重点,我想打印我在主线程或代码的主要部分中产生的内容。

python

4
推荐指数
1
解决办法
6586
查看次数