Python学习记录: 内置模块argparse

argparse

在看v8引擎的源码时候 看了一些python脚本工具,
如 https://github.com/v8/v8/blob/master/tools/wasm-compilation-hints/inject-compilation-hints.py
image

image

#!/usr/bin/env python

# Copyright 2019 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file.
# 导入模块
import argparse
import io
import sys

from wasm import *

FUNCTION_SECTION_ID = 3

def parse_args():
  # 创建一个解析对象
  # description 参数可以用于插入描述脚本用途的信息,可以为空于
  parser = argparse.ArgumentParser(\
      description="Inject compilation hints into a Wasm module.")
  # 向该对象中添加你要关注的命令行参数和选项
  parser.add_argument("-i", "--in-wasm-file", \
      type=str, \
      help="original wasm module")
  parser.add_argument("-o", "--out-wasm-file", \
      type=str, \
      help="wasm module with injected hints")
  parser.add_argument("-x", "--hints-file", \
      type=str, required=True, \
      help="binary hints file to be injected as a custom section " + \
          "'compilationHints'")
  # 进行解析
  return parser.parse_args()

if __name__ == "__main__":
  args = parse_args()
  in_wasm_file = args.in_wasm_file if args.in_wasm_file else sys.stdin.fileno()
  out_wasm_file = args.out_wasm_file if args.out_wasm_file else sys.stdout.fileno()
  hints_bs = open(args.hints_file, "rb").read()
  with io.open(in_wasm_file, "rb") as fin:
    with io.open(out_wasm_file, "wb") as fout:
      magic_number, bs = read_magic_number(fin);
      fout.write(bs)
      version, bs = read_version(fin);
      fout.write(bs)
      num_declared_functions = None
      while True:
        id, bs = read_varuintN(fin)
        fout.write(bs)
        if id == None:
          break
        payload_length, bs = read_varuintN(fin)
        fout.write(bs)

        # Peek into function section for upcoming validity check.
        if id == FUNCTION_SECTION_ID:
          num_declared_functions, bs = peek_varuintN(fin)

        bs = fin.read(payload_length)
        fout.write(bs)

        # Instert hint section after function section.
        if id == FUNCTION_SECTION_ID:
          assert len(hints_bs) == num_declared_functions, "unexpected number of hints"
          write_compilation_hints_section(fout, hints_bs)

参考

https://www.jianshu.com/p/a41...

阅读 218

推荐阅读
镜心的小树屋
用户专栏

方寸湛然GitHub组织地址:[链接]

47 人关注
123 篇文章
专栏主页