Python小工具之消耗系统指定大小内存的方法

yipeiwu_com5年前Python基础

工作中需要根据某个应用程序具体吃了多少内存来决定执行某些操作,所以需要写个小工具来模拟应用程序使用内存情况,下面是我写的一个Python脚本的实现。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import time

def print_help():
  print 'Usage: '
  print ' python mem.py 100MB'
  print ' python mem.py 1GB'

if __name__ == "__main__":
  if len(sys.argv) == 2:
    pattern = re.compile('^(\d*)([M|G]B)$')
    match = pattern.match(sys.argv[1].upper())
    if match:
      num = int(match.group(1))
      unit = match.group(2)
      if unit == 'MB':
        s = ' ' * (num * 1024 * 1024)
      else:
        s = ' ' * (num * 1024 * 1024 * 1024)

      time.sleep(10000)
    else:
      print_help()
  else:
    print_help()

使用方法如下:

python mem.py 100M
python mem.py 1G

以上这篇Python小工具之消耗系统指定大小内存的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python2和Python3中urllib库中urlencode的使用注意事项

前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urle...

python求最大连续子数组的和

抛出问题: 求一数组如 l = [0, 1, 2, 3, -4, 5, -6],求该数组的最大连续子数组的和 如结果为[0,1,2,3,-4,5] 的和为7 问题分析: 这个问题很...

python使用pip安装模块出现ReadTimeoutError: HTTPSConnectionPool的解决方法

今天使用pip安装第三库时,有时会报错: pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(hos...

python中使用urllib2伪造HTTP报头的2个方法

在采集网页信息的时候,经常需要伪造报头来实现采集脚本的有效执行 下面,我们将使用urllib2的header部分伪造报头来实现采集信息 方法1、 #!/usr/bin/python...

取numpy数组的某几行某几列方法

这个操作在numpy数组上的操作感觉有点麻烦,但是也没办法。 例如 a = [[1,2,3], [4,5,6], [7,8,9]] 取 a 的 2 3 行, 1 2 列...