为什么我的Python代码在10秒之后仍然继续运行?

2024-09-30 02:26:11 发布

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

我有一个代码,每100ms打印鼠标坐标(x,y)和时间戳。我要它运行10秒。就这样。在

因此,我实现了“多处理”,并将其初始化为从多处理函数内部调用主函数“printevery100ms”,并告诉它10秒后关闭。在

但它不会在10秒后关闭,而是跳过p.terminate()命令并继续运行。。。

代码在这里。

import multiprocessing
import time
import threading
import datetime


def printevery100ms():

    threading.Timer(.1,printevery100ms).start()
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')


  from ctypes import windll,Structure,c_int,byref

  class POINT(Structure):

     _fields_ = [("x",c_int),("y",c_int)]

  def queryMousePosition():

      pt = POINT()
      windll.user32.GetCursorPos(byref(pt))
      return {"x": pt.x,"y": pt.y}

  pos = queryMousePosition()

  print('{{\'x\': {}, \'y\': {}}}'.format(pos['x'],pos['y']),st)

printevery100ms()


if __name__ == '__main__':

        # Start printevery100ms as a process
        p = multiprocessing.Process(target=printevery100ms, name="printevery100ms", args=(10,))
        p.start()

        # Wait 10 seconds for printevery100ms

        time.sleep(10)
        # Terminate printevery100ms
        p.terminate()

        p.join()
        print "Not Terminated"

所以多处理代码初始化10秒计时器,它应该在10秒后关闭它,这是terminate命令的目的。我写了一个print命令来打印“notterminated”,如果代码在10秒后仍然没有停止;这正是发生的事情。在

结果如下:(9秒后..)

^{pr2}$

如您所见,它正在打印“Not terminated”,这意味着它运行了10秒,然后到达了terminate命令,但它继续运行,好像什么都没发生过一样。你能告诉我我做错了什么吗?或者这和多重处理有关吗?在


Tags: 代码posimport命令ptdatetimetimedef
1条回答
网友
1楼 · 发布于 2024-09-30 02:26:11

你的代码有几个问题:

  1. 从样式的角度来看,printevery100ms函数中有不同的缩进。在
  2. 我猜这就是问题所在:printevery100ms()在你的if __name__ == '__main__':之前被调用(就在第30行),并在你的主线程中运行函数,而这并没有停止。在
  3. multiprocessing.Process的调用使用参数(10,)调用printevery100ms,这将导致此调用失败。但是,仍然有主线程在运行,因此它似乎不会停止。在

解决方法如下:

import multiprocessing
import time
import threading
import datetime


def printevery100ms():

    threading.Timer(.1,printevery100ms).start()
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')


    from ctypes import windll,Structure,c_int,byref

    class POINT(Structure):

        _fields_ = [("x",c_int),("y",c_int)]

    def queryMousePosition():

        pt = POINT()
        windll.user32.GetCursorPos(byref(pt))
        return {"x": pt.x,"y": pt.y}

    pos = queryMousePosition()

    print('{{\'x\': {}, \'y\': {}}}'.format(pos['x'],pos['y']),st)

#printevery100ms() # HERES ISSUE NUMBER 2


if __name__ == '__main__':

        # Start printevery100ms as a process
        p = multiprocessing.Process(target=printevery100ms, name="printevery100ms", args=()) # FIXED ISSUE NUMBER 2
        p.start()

        # Wait 10 seconds for printevery100ms

        time.sleep(10)
        # Terminate printevery100ms
        p.terminate()

        p.join()
        print("Not Terminated")

相关问题 更多 >

    热门问题