"在另一个线程上调用os._exit()不会退出程序"

2024-09-28 22:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始一个新的线程:

self.thread = ThreadedFunc()
self.thread.start()

在发生一些事情之后,我想退出我的程序,所以我调用os._exit()

os._exit(1)

这个程序仍然有效。一切都是功能性的,只是看起来os._exit()没有执行。你知道吗

从不同的线程退出整个程序有不同的方法吗?如何解决这个问题?你知道吗

编辑:添加了更完整的代码示例。你知道吗

self.thread = DownloadThread()
self.thread.data_downloaded.connect(self.on_data_ready)
self.thread.data_progress.connect(self.on_progress_ready)
self.progress_initialized = False
self.thread.start()

class DownloadThread(QtCore.QThread):
    # downloading stuff etc.

    sleep(1)
    subprocess.call(os.getcwd() + "\\another_process.exe")
    sleep(2)
    os._exit(1)

编辑2:已解决!有一个quit()terminate()exit()函数用于停止线程。就这么简单。看看这些文件。你知道吗


Tags: self程序编辑dataosonconnectexit
1条回答
网友
1楼 · 发布于 2024-09-28 22:24:36

打电话给os._exit(1)对我很有用。 您应该使用标准库threading。你知道吗

我猜您正在使用multiprocessing,这是一个基于进程的“线程化”接口,它使用与threading类似的API,但是创建子进程而不是子线程。所以os._exit(1)只退出子进程,不影响主进程

您还应该确保在主线程中调用了join()函数。否则,操作系统可能会安排在开始在子线程中执行任何操作之前将主线程运行到底。你知道吗

你知道吗系统出口()不起作用,因为它与引发SystemExit异常相同。在线程中引发异常只会退出该线程,而不是整个进程。你知道吗

示例代码。{由ubuntu cd7测试。 返回代码按预期为1

import os
import sys
import time
import threading
# Python Threading Example for Beginners
# First Method
def greet_them(people):
    for person in people:
        print("Hello Dear " + person + ". How are you?")
        os._exit(1)
        time.sleep(0.5)
# Second Method
def assign_id(people):
    i = 1
    for person in people:
        print("Hey! {}, your id is {}.".format(person, i))
        i += 1
        time.sleep(0.5)

people = ['Richard', 'Dinesh', 'Elrich', 'Gilfoyle', 'Gevin']
t = time.time()
#Created the Threads
t1 = threading.Thread(target=greet_them, args=(people,))
t2 = threading.Thread(target=assign_id, args=(people,))
#Started the threads
t1.start()
t2.start()
#Joined the threads
t1.join()   # Cannot remove this join() for this example
t2.join()
# Possible to reach here if join() removed
print("I took " + str(time.time() - t))  

信用:示例代码是从https://www.simplifiedpython.net/python-threading-example/复制和修改的

相关问题 更多 >