【问题标题】:A function that wont stop/pause my script不会停止/暂停我的脚本的功能
【发布时间】:2016-08-13 15:54:24
【问题描述】:

我有一个for 循环,在循环内我用if 检查一些东西,当满足条件时,我启动一个函数。问题是这个函数包括一个等待期(time.sleep),我注意到循环暂停,直到该函数完成。

有什么方法可以让我的循环在函数执行时继续运行? 我在想也许会启动另一个脚本,但我什至不确定它是否也会暂停循环......

目标是能够在第一个功能完成之前再次启动该功能。

代码看起来像这样

def myfunction():
   time.sleep(30)
   print("waited 30 seconds...")
   do something
for something
   if condition:
      myfunction()
   print("the loop is resumed...")

【问题讨论】:

  • 发布实际代码而不是对其的描述。不过听起来你想要multiprocessing
  • 密码保密,抱歉
  • 没关系,我们不想要整件事;创建一个匿名的minimal reproducible example
  • 你试过使用线程吗?为什么调用新进程会阻塞当前进程?
  • 我不知道如何使用线程。我正在检查具有 2 个脚本并将第二个脚本作为模块导入的选项,但在我看来,它不会有任何区别,因为它会看到第二个文件的代码,就好像它是第一个文件的一部分一样。没有?

标签: python subprocess


【解决方案1】:

您描述的问题可以通过简单的线程来相当简单地解决,如下所示:

import time
import threading

def myfunction():
    time.sleep(30)
    print("waited 30 seconds.")
    # do whatever else

num = 0
mythreads = []
while(True):  # Just loop forever for demo purposes
    num += 1
    if num % 5 == 0:  # Execute the function once every 5 times
        newthread = threading.Thread(target=myfunction)
        mythreads.append(newthread)
        newthread.start()
    print("The loop is resumed.")

【讨论】:

  • 看起来不错,我会试试看。函数执行完毕,newt线程会自动停止吗?
  • 看起来它现在可以正常工作了。非常感谢!
  • @Seb 如果它对你有用,请接受答案。
猜你喜欢
  • 1970-01-01
  • 2015-02-12
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
相关资源
最近更新 更多