运行多个python线程的简单方法 [英] Simple way to run multiple python threads

查看:75
本文介绍了运行多个python线程的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从不同的目录导入多个python线程,然后希望同时运行它们.

I'm importing multiple python threads from different directories and then want to run them simultaneously.

这是我的父母

import sys
import thread

sys.path.append('/python/loanrates/test')

import test2

thread.start_new_thread(test2.main())

这是我孩子的一个:

import json 

def main():

    data = 'ello world'

    print data 

    with open( 'D:/python/loanrates/test/it_worked.json', 'w') as f:
        json.dump(data, f)

if __name__ == '__main__':
    main() 

但我收到此错误:

TypeError: start_new_thread expected at least 2 arguments, got 1

启动这个线程(然后使用相同的方法依次运行多个线程)的简单方法是什么

What is a simple way I can get this thread started (and then sequentially run multiple threads using the same method)

推荐答案

您还需要为元组提供运行参数的参数.如果没有,请传递一个空的元组.

You also need to provide a tuple with the argument to run the function with. If you have none, pass an empty tuple.

thread.start_new_thread(test2.main, ())

来自thread.start_new_thread(function, args[, kwargs])文档(粗体我的):

启动一个新线程并返回其标识符.线程使用自变量列表args(必须为元组)执行函数 function .可选的kwargs参数指定关键字参数的字典.当函数返回时,线程以静默方式退出.当该函数以未处理的异常终止时,将打印堆栈跟踪,然后线程退出(但其他线程继续运行).

Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

您还可以:

thread = Thread(target = test2.main, args, kwargs)

thread. start() // starts the thread

thread. join() // wait

此处中了解有关此方法的更多信息.

Read more on this approach to creating and working with threads here.

这篇关于运行多个python线程的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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