python - 限制脚本中的 Ram 使用
问题描述
我需要限制在 NiFi 中运行 Python 脚本时使用的内存量,我在 Stack Overflow 中找到了这个答案。我遵循代码如何工作的逻辑,但我对如何在 Python 脚本中实际实现它有点困惑。
例如,如果我有一个脚本
import sys
import json
flowFile = sys.stdin.read()
try:
j = json.loads(flowFile)
sys.stdout.write(j)
except:
sys.stdout.write(flowFile)
然后我会将内存限制实现为
import sys
import json
def memory_limit():
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard))
def get_memory():
with open('/proc/meminfo', 'r') as mem:
free_memory = 0
for i in mem:
sline = i.split()
if str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
free_memory += int(sline[1])
return free_memory
if __name__ == '__main__':
memory_limit() # Limitates maximun memory usage to half
try:
main()
except MemoryError:
sys.stderr.write('\n\nERROR: Memory Exception\n')
sys.exit(1)
flowFile = sys.stdin.read()
try:
j = json.loads(flowFile)
sys.stdout.write(j)
except:
sys.stdout.write(flowFile)
还是完全不同的东西?
解决方案
推荐阅读
- google-cloud-platform - 以编程方式获取 GCP 上的当前服务帐户
- matlab - cftool 不适合自定义拟合
- asp.net-core - How can I remove slash in route of controller?
- ios - how to select xcode version in fastlane when using github actions
- python - Smoothening a curve in Python
- ios - iOS Notification Extension to load media not called
- javascript - 跨浏览器扩展后台脚本导入错误
- android - WebView init 出现异常:无法创建锁定文件 webview_data.lock EACCES(权限被拒绝)
- python - 如何从值列表中自动填充 if/elif 块?
- symfony - 过滤器选择 Symfony Dom Crawler