【问题标题】:Parse arguments in sequential order (incl. repeated arguments) [.py]按顺序解析参数(包括重复的参数)[.py]
【发布时间】:2015-12-10 07:11:25
【问题描述】:

我正在编写一个生成序列波形的函数,并希望让用户指定序列中每个正弦波的频率和持续时间。

如何定义一个位置参数解析器,它可以采用以下形式的参数,这说明了每个开关的传递顺序?:

waveSequence.py --sine 440 1 --silence 0.5 --sine 110 2

(这将产生 1 秒的 440Hz 正弦波,然后是 0.5 秒的静音,然后是 2 秒的 110Hz 正弦波。)

这样的开关还能回收吗?


解决它的一种方法可能是按位置读取参数。在 bash 中,我可以这样做:

if [ $1 -eq 'sine' ]; then
    freq=$2
    time=$3
    shift
    shift
    shift
    # Next, continue reading from 4th argument
elif [ $1 -eq 'silence' ]; then
    # no freq, only time
    time=$2
    shift
    shift
else
    # other waveforms
fi

如何在 Python 中切换位置参数?

【问题讨论】:

  • 也许命令行界面不是这里最好的方法?

标签: python-2.7 arguments command-line-arguments sequence


【解决方案1】:

您也可以将sys.argv 用于原始参数字符串。

代码:

import sys
print sys.argv
$ python waveSequence.py --sine 440 1 --silence 0.5 --sine 110 2
['waveSequence.py', '--sine', '440', '1', '--silence', '0.5', '--sine', '110', '2']

【讨论】:

    【解决方案2】:

    我相信,没有办法进行定位 --option 参数。可能是,要走的路是使用带有常规位置参数的关键字,例如

    $ waveSequence.py sine-440-1 quiet-0.5 sine-110-2

    代码:

    from argparse import ArgumentParser
    
    parser = ArgumentParser(description="wave sequence generation")
    parser.add_argument("waves", type=str, nargs="+")
    
    args = parser.parse_args()
    
    for arg in args.waves:
        (type, spec) = arg.split("-", 1)
        if type == "sine":
            (freq, duration) = spec.split("-")
            print "Playing sine wave with frequency %s for %ss" % (freq, duration)
        elif type == "silence":
            duration = spec
            print "Silence for %ss" % duration
    

    输出:

    播放频率为440的正弦波1s
    静默 0.5 秒
    播放频率为 110 的正弦波 2s

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2012-07-15
      • 2020-05-24
      • 2013-08-21
      • 1970-01-01
      • 2012-12-18
      • 2018-07-15
      • 2013-06-03
      • 1970-01-01
      相关资源
      最近更新 更多