在 python 中打印命令行参数

Printing the command line arguments in python

我正在学习在 python 中传递命令行参数。我想打印参数,但我不断收到以下错误:

AttributeError: 'dict' 对象没有属性 'fft_length'

我的代码如下:

import argparse
import configlib

parser = configlib.add_parser("MFCC config")

parser.add_argument("-fft","--fft_length", type=int, default=512, metavar="", help="FFT length")
args = configlib.parse()

print(args.fft_length)

configlib的代码如下:

from typing import Dict, Any
import logging
import pprint
import sys
import argparse

# Logging for config library
logger = logging.getLogger(__name__)

# Our global parser that we will collect arguments into
parser = argparse.ArgumentParser(description=__doc__, fromfile_prefix_chars="@")

# Global configuration dictionary that will contain parsed arguments
# It is also this variable that modules use to access parsed arguments
config: Dict[str, Any] = {}


def add_parser(title: str, description: str = ""):
    """Create a new context for arguments and return a handle."""
    return parser.add_argument_group(title, description)


def parse(save_fname: str = "") -> Dict[str, Any]:
    """Parse given arguments."""
    config.update(vars(parser.parse_args()))
    logging.info("Parsed %i arguments.", len(config))
    # Optionally save passed arguments
    if save_fname:
        with open(save_fname, "w") as fout:
            fout.write("\n".join(sys.argv[1:]))
        logging.info("Saving arguments to %s.", save_fname)
    return config


def print_config():
    """Print the current config to stdout."""
    pprint.pprint(config)

你能帮我理解我做错了什么吗?

为了更好地理解您的代码,我将重写它作为一个简单的 argparse 使用。

parser = argparse.ArgumentParser()
new_group = parser.add_argument_group("MFCC config")
# assigning this to `parser` may be confusing
new_group.add_argument("-fft","--fft_length", type=int, default=512)
# args = configlib.parse()
# I think this is using configlib.parser, not the new_group
# 
args = parser.parse_args()
# then use this to update the `configlib.config dict
config.update(vars(args)
# then return the config dict as args  

所以如果我解析正确

args = configlib.parse()   # this is the config dict

这可以解释错误。 args 此时是 dict,而不是 argparse.Namespace

直接解析为:

args = configlib.parser.parse_args()   # returns a Namespace
print(args)        # diagnostic print
print(args.fft_length)

更改主脚本变量会有很大帮助:

newgroup = configlib.add_parser("MFCC config")
newgroup.add_argument("-fft","--fft_length", type=int, default=512, metavar="", help="FFT length")
configDict = configlib.parse()
print(configDict)    # diagnostic print
print(configDict[fft_length']