Python命令行参数赋值给变量

时间:2014-02-11 07:47:37

标签: python logic command-line-arguments

我必须将命令行参数存储在变量中或为其指定默认值。

我正在尝试的是以下

import sys
Var=sys.argv[1] or "somevalue"

如果我没有指定任何参数,我收到错误超出索引。怎么解决这个问题?

4 个答案:

答案 0 :(得分:7)

Var=sys.argv[1] if len(sys.argv) > 1 else "somevalue"

答案 1 :(得分:2)

好问题。

我认为最好的解决方案是

try:
    var = sys.argv[1]
except IndexError:
    var = "somevalue"

答案 2 :(得分:1)

内置argparse模块适用于这些类型的任务:

import argparse

# Set up argument parser
ap = argparse.ArgumentParser()

# Single positional argument, nargs makes it optional
ap.add_argument("thingy", nargs='?', default="blah")

# Do parsing
a = ap.parse_args()

# Use argument
print a.thingy

或者,如果您遇到Python 2.6或更早版本,并且不希望在backported argparse module上添加要求,您可以手动执行类似操作:

import optparse

opter = optparse.OptionParser()
# opter.add_option("-v", "--verbose") etc
opts, args = opter.parse_args()

if len(args) == 0:
    var = "somevalue"
elif len(args) == 1:
    var = args[0]
else:
    opter.error("Only one argument expected, got %d" % len(args))

print var

答案 3 :(得分:0)

使用命令行处理模板尝试以下操作:

def process_command_line(argv):
    ...
    # add your option here
    parser.add_option('--var',
        default="somevalue",
        help="your help text")

def main(argv=None):
    settings, args = process_command_line(argv)
    ...
    print settings, args # <- print your settings and args

使用下面的模板运行./your_script.py,上面的修改会打印{'var': 'somevalue'} []

有关命令行处理模板的示例,请参阅 Code Like a Pythonista:Idiomatic Python http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#command-line-processing)中的示例:

#!/usr/bin/env python

"""
Module docstring.
"""

import sys
import optparse

def process_command_line(argv):
    """
    Return a 2-tuple: (settings object, args list).
    `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
    """
    if argv is None:
        argv = sys.argv[1:]

    # initialize the parser object:
    parser = optparse.OptionParser(
        formatter=optparse.TitledHelpFormatter(width=78),
        add_help_option=None)

    # define options here:
    parser.add_option(      # customized description; put --help last
        '-h', '--help', action='help',
        help='Show this help message and exit.')

    settings, args = parser.parse_args(argv)

    # check number of arguments, verify values, etc.:
    if args:
        parser.error('program takes no command-line arguments; '
                     '"%s" ignored.' % (args,))

    # further process settings & args if necessary

    return settings, args

def main(argv=None):
    settings, args = process_command_line(argv)
    # application code here, like:
    # run(settings, args)
    return 0        # success

if __name__ == '__main__':
    status = main()
    sys.exit(status)