【问题标题】:Is it possible to renice a subprocess?是否可以修改子流程?
【发布时间】:2011-01-28 15:27:06
【问题描述】:

我知道os.nice() 它非常适合父进程,但我需要对我的子子进程进行 renice。我找到了这样做的方法,但它似乎不是很方便而且过于过度:

os.system("renice -n %d %d" % ( new_nice, suprocess.pid ) )

并且它不是在重新调整后返回结果良好的水平。

有没有更简洁的方式来在 python 中修改子进程?

【问题讨论】:

    标签: python subprocess nice renice


    【解决方案1】:

    使用subprocess.Popenpreexec_fn参数:

    如果preexec_fn 设置为可调用对象,则该对象将在子进程执行之前在子进程中调用。 (仅限 Unix)

    例子:

    >>> Popen(["nice"]).communicate()
    0
    (None, None)
    >>> Popen(["nice"], preexec_fn=lambda : os.nice(10)).communicate()
    10
    (None, None)
    >>> Popen(["nice"], preexec_fn=lambda : os.nice(20)).communicate()
    19
    (None, None)
    

    【讨论】:

      【解决方案2】:

      您应该使用subprocess.Popen 而不是os.system,这样您就可以访问打印到 sys.stdout 的任何结果。 IIRC,os.system 只允许您访问返回值,这可能是 '0' 而不是很好的级别。

      【讨论】:

        【解决方案3】:

        renice 通常由 set/getpriority 实现,它似乎还没有进入 python os 或 posix 模块(还没有?)。所以现在调用 renice 系统命令似乎是你最好的选择。

        作为替代方案,您可以在创建子进程之前 os.nice 父进程 - 这将继承其父进程的 nice 值 - 并在创建子进程后再次返回 os.nice。

        【讨论】:

        • 他可以使用 ctypes 调用 setpriority/getpriority。
        【解决方案4】:

        没有适当的权利,你只能以一种方式放弃

        【讨论】:

          【解决方案5】:

          我过去用 CLI 创建了一个 python 脚本。你可以在这里找到它:https://github.com/jedie/python-code-snippets/blob/master/CodeSnippets/reniceall.py

          【讨论】:

            【解决方案6】:

            renice 通常由 set/getpriority 实现,它似乎还没有进入 python os 或 posix 模块(还没有?)。所以现在调用 renice 系统命令似乎是你最好的选择。

            扩展丹尼尔对ctypes的评论:

            from ctypes import cdll
            libc = cdll.LoadLibrary("libc.so.6")
            
            for pid in pids:
                print("old priority for PID", pid, "is", libc.getpriority(0, pid))
                libc.setpriority(0, pid, 20)
                print("new priority for PID", pid, "is", libc.getpriority(0, pid))
            

            结果:

            old priority for PID 9721 is 0
            new priority for PID 9721 is 19
            

            【讨论】:

              猜你喜欢
              • 2011-04-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-04-06
              • 2012-05-26
              • 1970-01-01
              • 1970-01-01
              • 2012-05-18
              相关资源
              最近更新 更多