【问题标题】:Nicing a running python process?喜欢一个正在运行的 python 进程?
【发布时间】:2012-12-05 21:48:43
【问题描述】:

当我的运行时间较长的程序启动时,我想降低它的优先级,这样它就不会消耗它运行的机器上的所有可用资源。环境使程序有必要限制自己。

有没有我可以使用的类似 python 的命令,这样程序就不会利用它正在运行的计算机的全部容量?

【问题讨论】:

    标签: python nice


    【解决方案1】:

    您始终可以使用nice pythonscript 运行该进程,

    但如果你想在脚本中设置 nice-level,你可以这样做:

    import os
    os.nice(20)
    

    脚本运行的时间越长,您可以逐步增加 nice 级别,因此随着时间的推移,它使用的资源越来越少,这很简单,只需将其集成到脚本中即可。

    或者,在脚本之外,一旦它运行,您应该能够使用renice -p <pid>

    【讨论】:

    • 通常需要注意的是,除非以root(或类似)身份运行,否则您不能nice "down"
    • Nice 从-20 取一个号码到+20。普通用户nice up,最大up-value为20。特权用户可以很好地降低到-20 的最小降低值。该调用请求通过选择的值调整 nice 级别,因此为了 nice(并使用更少的 CPU),您使用正值。为了“降低”,您使用负值。
    • 这会影响子进程吗?
    【解决方案2】:

    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])
    

    【讨论】:

    • 适用于 Windows - 但除非 nice 是一个通用术语,否则我认为它是基于 *nix 的
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2012-09-26
    • 2014-07-04
    • 2019-12-05
    相关资源
    最近更新 更多