简体   繁体   English

当它达到内存限制时退出Python程序

[英]Quit Python program when it hits memory limit

I have a couple of Python/Numpy programs that tend to cause the PC to freeze/run very slowly when they use too much memory. 我有几个Python / Numpy程序,当它们使用太多内存时,往往会导致PC冻结/运行速度非常慢。 I can't even stop the scripts or move the cursor anymore, when it uses to much memory (eg 3.8/4GB) Therefore, I would like to quit the program automatically when it hits a critical limit of memory usage, eg 3GB. 当它用于大量内存(例如3.8 / 4GB)时,我甚至无法停止脚本或移动光标。因此,我想在达到内存使用的关键限制(例如3GB)时自动退出程序。

I could not find a solution yet. 我找不到解决方案了。 Is there a Pythonic way to deal with this, since I run my scripts on Windows and Linux machines. 是否有Pythonic方法来解决这个问题,因为我在Windows和Linux机器上运行我的脚本。

You could limit the process'es memory limit, but that is OS specific. 您可以限制进程的内存限制,但这是特定于操作系统的。

Another solution would be checking value of psutil.virtual_memory() , and exiting your program if it reaches some point. 另一种解决方案是检查psutil.virtual_memory()值,并在程序达到某一点时退出程序。

Though OS-independent, the second solution is not Pythonic at all. 虽然与操作系统无关,但第二种解决方案根本不是Pythonic。 Memory management is one of the things we have operating systems for. 内存管理是我们拥有操作系统的东西之一。

I'd agree that in general you want to do this from within the operating system - only because there's a reliability factor in having "possibly runaway code check itself for possibly runaway behavior" 我同意通常你想在操作系统中做到这一点 - 只是因为有一个可靠性因素“可能失控的代码检查自己可能失控的行为”

If a hard and fast requirement is to do this WITHIN the script, then I think we'd need to know more about what you're actually doing. 如果要求在脚本中执行此操作,那么我认为我们需要更多地了解您实际在做什么。 If you have a single large data structure that's consuming the majority of the memory, you can use sys.getsizeof to identify how large that structure is, and throw/catch an error if it gets larger than you want. 如果您有一个占用大部分内存的单个大型数据结构,则可以使用sys.getsizeof来确定该结构的大小,如果它变得比您想要的大,则抛出/捕获错误。

But without knowing at least a little more about the program structure, I think it'll be hard to help... 但是,如果不了解程序结构的更多信息,我认为很难帮助......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM