我的9行Python代码正在使用100%的CPU [英] My 9 Line of Python code is using 100% of My CPU

查看:198
本文介绍了我的9行Python代码正在使用100%的CPU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本(test.py),需要使用以下代码每10-15分钟重新启动一次:

I have a python script (test.py) that need to be restarted every 10 - 15 minutes using below code :

import subprocess,time
WAIT=700
file_name = ("test.py")
while True:
    process=subprocess.Popen("python "+ file_name)
    now=time.time()
    while time.time() - now < WAIT:
        pass
    process.kill()

但是花费100%我的CPU。有什么问题吗?如果我只运行test.py,则一切正常。

But is taking 100% of my CPU . What can be wrong ? if i run test.py only everything is normal .

推荐答案

您应该使用 .sleep 函数,该函数不会使用CPU密集的while循环:

You should use the .sleep function, which won't use a cpu intensive while-loop:

import subprocess,time
WAIT=700
file_name = ("test.py")
while True:
    process=subprocess.Popen("python "+ file_name)
    time.sleep(WAIT)
    process.kill()

这篇关于我的9行Python代码正在使用100%的CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆