在python中运行进程时执行某些操作
在一个过程之间做些别的事情 我想用python运行一个进程,我想当进程花费超过10秒时,做一些事情,比如打印(等待它完成) 此打印必须在进程运行时打印在python中运行进程时执行某些操作,python,performance,time,Python,Performance,Time,在一个过程之间做些别的事情 我想用python运行一个进程,我想当进程花费超过10秒时,做一些事情,比如打印(等待它完成) 此打印必须在进程运行时打印 如果您知道如何在代码中执行此操作,请告诉我您可以使用时间模块 下面是一个非常基本的例子: import time t0 = time.time() m = 'hello world' print(m) for i in range(5): t1 = time.time() if t1 - t0 > 10:
如果您知道如何在代码中执行此操作,请告诉我您可以使用时间模块 下面是一个非常基本的例子:
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)
还有其他方法,例如
线程化
您应该使用线程化
对应用程序进行多线程处理
e、 g:
输出(在REPL上):
输出(从文件运行时):
关于线程的进一步阅读:欢迎来到Stackoverflow,请阅读。特别注意。确保用正确的标签(编程语言、相关技术等)标记问题。你在发布一个好的问题上投入的精力越多:一个容易阅读、理解的问题,而且这个问题越容易吸引相关的人,你得到帮助的速度就越快。祝你好运
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")
$ 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