更新时间:2023-02-22 09:39:36
您可以使用argparse
解析命令行参数,然后根据需要进行修改.但是,目前,argparse
缺少反向操作并将这些值转换回命令行字符串的功能.但是,有一个用于精确执行此操作的程序包,称为 argunparse
.例如,cmd.py
You can use argparse
to parse the command-line arguments, and then modify those as desired. At the moment however, argparse
lacks the functionality to work in reverse and convert those values back into a command-line string. There is however a package for doing precisely that, called argunparse
. For example, the following code in cmd.py
import sys
import argparse
import argunparse
parser = argparse.ArgumentParser()
unparser = argunparse.ArgumentUnparser()
parser.add_argument('--foo')
parser.add_argument('--step', type=int)
kwargs = vars(parser.parse_args())
kwargs['step'] += 1
prefix = f'python {sys.argv[0]} '
arg_string = unparser.unparse(**kwargs)
print(prefix + arg_string)
将打印所需的命令行:
python cmd.py --foo=bar --step=1