[Python]除过parser的另外一种读取命令行的方法

读取命令行参数的方式

$python main.py -m TransE -d FB15K
对于上面的命令行程序,我们通过argv[0]获取到的就是程序的名字 main.pyargv[1]就是第一个参数-m,这里使用了一个小技巧arguments = arguments[1:]使得每次前进一位

while arguments:  # While there are arguments left to parse...
    if arguments[0][0] == '-':  # Found a "-name value" pair.
        opts[arguments[0]] = arguments[1]  # Add key and value to the dictionary.
    arguments = arguments[1:]  # Reduce the argument list by copying it starting from index 1.
from sys import argv

def getopts(arguments):
    opts = {}  # Empty dictionary to store key-value pairs.
    while arguments:  # While there are arguments left to parse...
        if arguments[0][0] == '-':  # Found a "-name value" pair.
            opts[arguments[0]] = arguments[1]  # Add key and value to the dictionary.
        arguments = arguments[1:]  # Reduce the argument list by copying it starting from index 1.
    return opts

current_models = ["SimplE_ignr", "SimplE_avg", "ComplEx", "TransE"]
current_datasets = ["wn18", "fb15k"]

opts = getopts(argv)
if not "-m" in opts:
    print("Please specify the model name using -m.")
    exit()
if not opts["-m"] in current_models:
    print("Model name not recognized.")
    exit()

if not "-d" in opts:
    print("Please specify the dataset using -d.")
    exit()

if not opts["-d"] in current_datasets:
    print("Dataset not recognized.")
    exit()

model_name = opts["-m"]
dataset = opts["-d"]

你可能感兴趣的:([Python]除过parser的另外一种读取命令行的方法)