【问题标题】:Do something while a process is running in python在 python 中运行进程时做某事
【发布时间】:2021-05-30 07:28:33
【问题描述】:
在一个进程之间做些别的事情
我想在 python 中运行一个进程,并且我希望当进程花费 超过 10 秒时,执行一些操作,例如 print(等待它完成。)
此打印必须在进程运行时打印
如果你知道如何在我的代码中做到这一点,请告诉我
【问题讨论】:
标签:
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。