在一个进程之间执行其他操作
我想在python中运行一个进程,当进程花费超过10秒时,我想做一些事情,比如打印(等待它完成。(
该打印必须在进程运行时打印
如果你知道我如何在代码中做到这一点,请告诉我
您应该使用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/
您可以使用时间模块。
这里有一个非常基本的例子:
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
。