简体   繁体   English

Python命令行参数赋值给变量

[英]Python command line argument assign to a variable

I have to either store the command line argument in a variable or assign a default value to it. 我必须将命令行参数存储在变量中或为其分配默认值。

What i am trying is the below 我正在尝试的是下面

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

I am getting the error out of index if i don't specify any argument. 如果我没有指定任何参数,我将从索引中获取错误。 How to solve this? 怎么解决这个?

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

Good question. 好问题。

I think the best solution would be to do 我认为最好的解决方案就是做

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

The builtin argparse module is intended for exactly these sorts of tasks: 内置的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

Or, if you are stuck with Python 2.6 or earlier, and don't wish to add a requirement on the backported argparse module , you can do similar things manually like so: 或者,如果您遇到Python 2.6或更早版本,并且不希望在反向移植的argparse模块上添加要求,您可以手动执行类似的操作:

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

Try the following with a command-line-processing template: 使用命令行处理模板尝试以下操作:

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

Running ./your_script.py with the template below and your modifications above prints {'var': 'somevalue'} [] 运行./your_script.py并使用下面的模板和上面的修改打印{'var': 'somevalue'} []

For an example of a command-line-processing template see an example in Code Like a Pythonista: Idiomatic Python ( http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#command-line-processing ): 有关命令行处理模板的示例,请参阅代码如Pythonista:惯用Python中的示例( http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#command-line-处理 ):

#!/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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM