【问题标题】:Do something while a process is running in python在 python 中运行进程时做某事
【发布时间】:2021-05-30 07:28:33
【问题描述】:

在一个进程之间做些别的事情

我想在 python 中运行一个进程,并且我希望当进程花费 超过 10 秒时,执行一些操作,例如 print(等待它完成。)

此打印必须在进程运行时打印

如果你知道如何在我的代码中做到这一点,请告诉我

【问题讨论】:

  • 欢迎来到 Stackoverflow,请阅读How To Ask。特别关注How To Create MCVE。确保使用适当的标签(编程语言、相关技术等)标记您的问题。您在发布一个好问题上付出的努力越多:一个易于阅读、理解并且是 on topic 的问题 - 它吸引相关人员的机会就越高,您将更快地获得帮助。祝你好运!

标签: python performance time


【解决方案1】:

您应该使用thread 来多线程您的应用程序。

例如:

import time
import threading

def long_running():
  print("long_running started")
  time.sleep(10)
  print("long_running finished")

x = threading.Thread(target=long_running)
x.start()
print("running something while long_running is running in background")

输出(在 REPL 上):

$ python3
Python 3.9.5 (default, May  9 2021, 14:00:28) 
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> import threading
>>> 
>>> def long_running():
...   print("long_running started")
...   time.sleep(10)
...   print("long_running finished")
... 
>>> x = threading.Thread(target=long_running)
>>> x.start()
long_running started
>>> print("running something while long_running is running in background")
running something while long_running is running in background
>>> long_running finished

输出(从文件运行时):

$ python3 /tmp/a.py
long_running started
running something while long_running is running in background
long_running finished

关于线程的进一步阅读:https://realpython.com/intro-to-python-threading/

【讨论】:

    【解决方案2】:

    您可以使用时间模块。

    这是一个非常基本的例子:

    import time
    
    t0 = time.time()
    
    m = 'hello world'
    print(m)
    
    for i in range(5):
        t1 = time.time()
        if t1 - t0 > 10:
            print('more than 10 seconds has passed')
        time.sleep(5)
        print('test', i)
    

    还有其他方法,比如threading

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      相关资源
      最近更新 更多