优雅地结束一个正在运行的Python进程?

16

当我的长时间运行的程序开始时,我希望降低它的优先级,以便它不会消耗运行机器上的所有资源。情况使得必须限制该程序的使用。

有没有一种像 Python 命令这样的好方法,可以让该程序不利用其运行计算机的全部容量?

2个回答

27

你可以通过运行nice pythonscript来始终以“优先级”方式运行进程,

但如果你想在脚本中设置“优先级”,可以这样做:

import os
os.nice(20)

您可以逐步增加脚本运行的好感度,这样它在运行一段时间后就会利用越来越少的资源,只需将其集成到脚本中即可。

或者,在脚本外部运行后,您应该能够使用renice -p <pid>


1
通常情况下,除非以“root”(或类似)身份运行,否则无法将“nice”降低。 - Jon Clements
4
Nice 命令接受从 -20+20 的数字。普通用户能够nice操作,最高可提升 20 级。特权用户可以进行nice降级,最低可调至 -20 级。该命令是用于请求通过所选的值来调整nice级别,使用正数值表示nice(以使用更少的CPU),使用负数值表示降低nice级别。 - Anya Shenanigans
这会影响子进程吗? - Basil
@Basil 是的。包括使用线程模块启动的独立线程进程。 - SurpriseDog

7

psutil似乎是一个跨平台的解决方案,用于为Python设置进程优先级。

https://github.com/giampaolo/psutil

Windows特定的解决方案: http://code.activestate.com/recipes/496767/

def setpriority(pid=None,priority=1):
""" Set The Priority of a Windows Process.  Priority is a value between 0-5 where
    2 is normal priority.  Default sets the priority of the current
    python process but can take any valid process ID. """

import win32api,win32process,win32con

priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
                   win32process.BELOW_NORMAL_PRIORITY_CLASS,
                   win32process.NORMAL_PRIORITY_CLASS,
                   win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                   win32process.HIGH_PRIORITY_CLASS,
                   win32process.REALTIME_PRIORITY_CLASS]
if pid == None:
    pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, priorityclasses[priority])

2
方便Windows使用 - 但除非“nice”是一个通用术语,否则我认为它是基于*nix的。 - Jon Clements

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接