python - 在 python 中创建线程

我有一个脚本,我希望一个函数与另一个函数同时运行。

我看过的示例代码:

import threading

def MyThread (threading.thread):
    # doing something........

def MyThread2 (threading.thread):
    # doing something........

MyThread().start()
MyThread2().start()

我无法正常工作。我更愿意使用线程函数而不是类来实现这一点。

这是工作脚本:

from threading import Thread

class myClass():

    def help(self):
        os.system('./ssh.py')

    def nope(self):
        a = [1,2,3,4,5,6,67,78]
        for i in a:
            print i
            sleep(1)


if __name__ == "__main__":
    Yep = myClass()
    thread = Thread(target = Yep.help)
    thread2 = Thread(target = Yep.nope)
    thread.start()
    thread2.start()
    thread.join()
    print 'Finished'

最佳答案

您不需要使用 Thread 的子类来完成这项工作 - 请查看我在下面发布的简单示例,了解如何操作:

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print("thread finished...exiting")

这里我展示了如何使用线程模块来创建一个调用普通函数作为其目标的线程。你可以看到我如何在线程构造函数中传递我需要的任何参数。

https://stackoverflow.com/questions/2905965/

相关文章:

python - 在类方法上使用 property()

linux - 如何获取 Docker 中依赖的子镜像列表?

android - Ubuntu - 错误 : Failed to create the SD ca

linux - 如何从文本文件中删除换行符?

linux - 如何计算每个目录中的文件数?

python - 导入语句python3的变化

python - 如何使用 Python 发送电子邮件?

python - Python中的字符串如何格式化 boolean 值?

linux - 错误 : Can't open display: (null) when using

Linux - 替换文件名中的空格