ZetCode

Python os.nice 函数

上次修改时间:2025 年 4 月 11 日

本全面指南探讨了 Python 的 os.nice 函数,该函数用于调整类 Unix 系统上的进程优先级(nice 值)。我们将介绍 nice 值范围、权限要求和实际示例。

基本定义

os.nice 函数将进程的 nice 值增加指定的增量。较高的 nice 值意味着较低的优先级。

关键参数:increment(要添加到当前 nice 值的值)。返回新的 nice 值。仅在 Unix 系统上可用,需要适当的权限。

基本 Nice 值调整

此示例演示了 os.nice 的最简单用法,即增加进程的 nice 值。正值降低优先级,负值提高优先级。

basic_nice.py
import os

# Increase nice value by 5 (lower priority)
try:
    new_nice = os.nice(5)
    print(f"New nice value: {new_nice}")
except PermissionError:
    print("Permission denied: need appropriate privileges")
except AttributeError:
    print("os.nice not available on this platform")

这尝试将 nice 值增加 5。在 Unix 上,普通用户只能增加 nice 值(降低优先级)。降低需要权限。

该示例包括针对权限问题和平台不兼容性的错误处理。

检查当前 Nice 值

要检查当前的 nice 值而不更改它,我们可以使用 os.nice(0)。这将返回当前的 nice 值而不进行修改。

check_nice.py
import os

try:
    current_nice = os.nice(0)
    print(f"Current nice value: {current_nice}")
    
    # Typical range is -20 (highest priority) to 19 (lowest)
    print("Lower values mean higher priority")
    
except AttributeError:
    print("os.nice not supported on this platform")

这显示了如何获取当前的 nice 值。值 0 表示默认优先级。负值表示高于默认优先级的优先级。

请注意,精确的范围(-20 到 19)和行为可能在 Unix 系统之间略有不同。

逐步降低优先级

此示例显示了如何通过逐步增加 nice 值来逐步降低进程优先级。

gradual_nice.py
import os
import time

def cpu_intensive_task():
    # Simulate CPU work
    for i in range(5):
        sum(range(10**6))
        print(f"Step {i} completed")

try:
    print(f"Initial nice: {os.nice(0)}")
    
    # First priority reduction
    os.nice(5)
    print(f"After first adjustment: {os.nice(0)}")
    cpu_intensive_task()
    
    # Further reduction
    os.nice(5)
    print(f"After second adjustment: {os.nice(0)}")
    cpu_intensive_task()
    
except PermissionError:
    print("Need privileges for negative adjustments")
except AttributeError:
    print("Platform doesn't support nice values")

该代码演示了多次调用 os.nice 如何逐步降低进程优先级。每次调整都会使该进程对其他进程更加“友好”。

实际上,您通常会设置一次 nice 值,而不是逐步设置。

设置最大 Nice 值

此示例尝试将进程设置为最大 nice 值(最低优先级)。普通用户通常可以设置最高为 19 的值。

max_nice.py
import os

MAX_NICE = 19  # Typical maximum nice value

try:
    current = os.nice(0)
    needed = MAX_NICE - current
    
    if needed > 0:
        new_nice = os.nice(needed)
        print(f"Set to maximum nice value: {new_nice}")
    else:
        print(f"Already at or above maximum nice: {current}")
        
except PermissionError:
    print("Permission denied for nice adjustment")
except AttributeError:
    print("Nice values not supported on this platform")

该代码计算达到最大 nice 值所需的增量。它仅在当前值低于最大值时才进行调整。

请注意,某些系统可能具有不同的最大值或限制。

特权 Nice 调整

此示例演示了特权进程(如 root)如何降低 nice 值以提高进程优先级。需要超级用户权限。

privileged_nice.py
import os
import sys

def check_root():
    if os.geteuid() != 0:
        print("This script requires root privileges")
        sys.exit(1)

try:
    check_root()
    current = os.nice(0)
    print(f"Current nice (as root): {current}")
    
    # Increase priority (decrease nice)
    new_nice = os.nice(-5)
    print(f"New nice value: {new_nice}")
    
except PermissionError:
    print("Unexpected permission error")
except AttributeError:
    print("Platform doesn't support nice adjustments")

该脚本首先验证 root 权限,然后演示降低 nice 值以提高进程优先级。

只有特权用户才能将 nice 值降低到当前值以下或低于 0。

子进程中的 Nice 值

此示例显示了 nice 值如何由子进程继承以及如何独立调整它们。

child_process.py
import os
import time

def worker():
    print(f"Child nice: {os.nice(0)}")
    time.sleep(2)

try:
    print(f"Parent nice: {os.nice(0)}")
    
    # Create child process
    pid = os.fork()
    
    if pid == 0:  # Child process
        # Adjust child's nice value
        os.nice(5)
        worker()
        os._exit(0)
    else:  # Parent process
        os.waitpid(pid, 0)
        print(f"Parent nice after child: {os.nice(0)}")
        
except AttributeError:
    print("Platform lacks fork or nice support")
except OSError:
    print("Fork failed")

父进程创建一个子进程,该子进程调整自己的 nice 值。父进程的 nice 值保持不变,这表明可以独立调整。

当您希望后台任务的优先级低于主进程时,此模式非常有用。

平台兼容性检查

此示例演示了如何检查 os.nice 的可用性并为不受支持的平台实现回退。

platform_check.py
import os
import sys

def adjust_priority(increment):
    if hasattr(os, 'nice'):
        try:
            return os.nice(increment)
        except PermissionError:
            print("Warning: No permission to adjust priority")
            return os.nice(0)
    else:
        print("Warning: Nice values not supported on this platform")
        return 0  # Default priority

# Usage
current_priority = adjust_priority(5)
print(f"Current priority adjustment: {current_priority}")

该代码首先检查 os.nice 的可用性,然后再尝试使用它。这使代码在不同的操作系统上更具可移植性。

Windows 系统不支持 nice 值,因此此检查对于跨平台代码至关重要。

安全注意事项

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程