サンプルプログラム集
提供: Wikinote
C
Python
memcurses.py
curses (libcurses) を利用した /proc/meminfo の変化量を表示するスクリプト。
ソースコード <toggledisplay>
#!/usr/bin/env python import sys, time, curses def main(argv): win = curses.initscr() if len(argv) > 1: interval = int(argv[1]) else: interval = 1 f = open("/proc/meminfo", "r") prev = [] while True: win.clear() win.addstr(0, 0, "Every %d.0s : %s" % (interval, time.ctime())) i = 0 try: for line in f: win.addstr(i+2, 0, line[:-1]) cur = line.split()[1] try: if cur != prev[i]: win.addstr(" %+d" % (int(cur) - int(prev[i]))) prev[i] = cur except IndexError: prev.append(cur) i += 1 win.addstr("\n") win.refresh() f.seek(0) time.sleep(interval) except KeyboardInterrupt: break curses.endwin() f.close() return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
</toggledisplay>
実行例 <toggledisplay>
$ ./memcurses.py 5 Every 5.0s : Sat Feb 26 01:06:31 2011 MemTotal: 5968984 kB MemFree: 458472 kB Buffers: 292224 kB +8 Cached: 4135716 kB SwapCached: 0 kB Active: 2248520 kB +44 Inactive: 2798728 kB HighTotal: 5241152 kB HighFree: 449732 kB LowTotal: 727832 kB LowFree: 8740 kB SwapTotal: 6144852 kB SwapFree: 6144716 kB Dirty: 456 kB Writeback: 0 kB AnonPages: 619336 kB +32 Mapped: 1179140 kB +112 Slab: 111936 kB -44 PageTables: 12296 kB +52 NFS_Unstable: 0 kB Bounce: 0 kB CommitLimit: 9129344 kB Committed_AS: 1629408 kB VmallocTotal: 116728 kB VmallocUsed: 19364 kB VmallocChunk: 97136 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 Hugepagesize: 2048 kB
</toggledisplay>
calc_buddy.py
/proc/buddyinfo のそれぞれのゾーンの合計サイズを計算するスクリプト。 タイムスタンプを付けて記録したファイルにも対応。
ソースコード <toggledisplay>
#!/usr/bin/env python import sys if len(sys.argv) == 1: files = [ open('/proc/buddyinfo', 'r') ] ts_shift = 4; else: files = [ open(f) for f in sys.argv[1:] ] ts_shift = 6; for file in files: for line in file: if len(line) > 1: print line[:-1], fields = line.split() total = 0 for val in range(0,11): total += int(fields[ts_shift + val]) * 4 * 2**val print total, "KB" else: print line, file.close() </toggledisplay>
実行例 <toggledisplay>
$ ./calc_buddy.py Node 0, zone DMA 46 5 3 0 0 0 0 1 1 1 0 3856 KB Node 0, zone Normal 327 2 1 1 1 1 1 0 0 0 1 5916 KB Node 0, zone HighMem 78051 15607 279 2 59 17 2 0 0 0 0 448052 KB
</toggledisplay>
dec2bin.py
10 進数を 2 進数に変換するスクリプト。32 ビット限定。
ソースコード <toggledisplay>
#!/usr/bin/env python import sys def dec2bin(dec): ret = "" for i in range(31, -1, -1): if dec & (1 << i): ret += "1" elif ret: ret += "0" return ret if __name__ == "__main__": if len(sys.argv) < 2: print "Usage: %s dec" % sys.argv[0] sys.exit(1) try: print dec2bin(int(sys.argv[1])) except ValueError: print "Invalid number" sys.exit(1)
</toggledisplay>
実行例 <toggledisplay>
$ ./dec2bin.py 12345 11000000111001 $ ./dec2bin.py 1024 10000000000 $ ./dec2bin.py -65536 11111111111111110000000000000000 $ ./dec2bin.py 2147483647 1111111111111111111111111111111 $ ./dec2bin.py -2147483648 10000000000000000000000000000000
</toggledisplay>