问题描述
我正在为诸如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 (将#修改为@)