微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过psutil获得最大的进程内存使用率

如何解决通过psutil获得最大的进程内存使用率

我正在为诸如Codeforces之类的竞赛系统编写问题解决方案检查器。这是用于Python提交的check_test函数

class PythonTestChecker:
    @staticmethod
    def compile(solution,time_limit,memory_limit):
        with open('temp/solution.py','w+') as f:
            f.write(solution)

    @staticmethod
    def check_test(test,solution,memory_limit):
        MAX_MEMORY = memory_limit * 1024 * 1024

        with open('temp/input.txt','w+') as f:
            f.write(test.input_data)

        start_time = time()
        try:
            run = subprocess.Popen([PYTHON_COMMAND,"temp/solution.py"],stdin=open('temp/input.txt','r'),stdout=open('temp/output.txt','w+'),stderr=open('temp/error.txt','w+'))
            proc = psutil.Process(run.pid)

            if os.name == "posix":
                proc.rlimit(psutil.RLIMIT_AS,(MAX_MEMORY,MAX_MEMORY))

            proc.wait(timeout=time_limit)

            end_time = time()
            process_time = int((end_time - start_time) * 1000)

            if open("temp/error.txt").read():
                raise subprocess.CalledProcessError(-1,PYTHON_COMMAND)
        except subprocess.CalledProcessError as e:
            end_time = time()
            process_time = int((end_time - start_time) * 1000)
            error = open('temp/error.txt').read().strip().split('\n')[-1].split(':')[0]
            if error == 'SyntaxError':
                return CompilationErrorVerdict()
            elif error == 'MemoryError':
                return MemoryLimitVerdict(time=process_time)
            return RuntimeErrorVerdict(time=process_time)
        except psutil.TimeoutExpired:
            proc.kill()
            end_time = time()
            process_time = int((end_time - start_time) * 1000)
            return TimeLimitVerdict(time=process_time)

        with open('temp/output.txt') as f:
            output = f.read().strip()

        if output == test.output_data:
            return OKVerdict(time=process_time)
        return WrongAnswerVerdict(time=process_time)

如您所见,我通过psutil限制了最大内存使用量。问题是:
—当内存到期时,Python脚本会将其写入stderr并退出。因此,唯一识别内存不足的方法是读取error.txt(这是stderr重新翻译器)并搜索MemoryError(我以相同的方式识别语法错误)。这是不好的hack,我想逃避它。此外,我无法将此方法应用于其他语言,而不是Python。
—我无法获得进程的最大内存使用率。我尝试在run.communicate()之后和run之后调用proc.wait(),但是它总是返回(None,None)。顺便说一下,据我所知,这不是最大内存,而是当前的内存使用情况。

我该如何解决?也许我应该避免使用psutil搜索其他计算机资源库?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。