Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从命令行解析参数_Python - Fatal编程技术网

Python从命令行解析参数

Python从命令行解析参数,python,Python,我有一个关于在Python中传递参数的问题 1.python run.py -create vairbale1 -reference variable2 many more variables 2.python run.py -get -list variable many more variable 如何使用optpass或getopt在脚本中实现这一点,如果参数无效,则需要打印无效参数 from optparse import OptionParser parser = Optio

我有一个关于在Python中传递参数的问题

1.python run.py -create vairbale1 -reference variable2 many more variables
2.python run.py  -get -list variable many more variable
如何使用optpass或getopt在脚本中实现这一点,如果参数无效,则需要打印无效参数

 from optparse import OptionParser

 parser = OptionParser()

这是我用过的一个片段。我为我工作,不过您可能需要更改参数类型

parser = OptionParser()
parser.add_option('-n', '--db_name', help='DB Name (comma separated if multiple DBs - no spaces)')
parser.add_option('-H', '--db_host', help='DB host (comma separated if multiple DBs - no spaces)')
parser.add_option('-p', '--db_port', help='DB port (optional)')
parser.add_option('-u', '--db_user', help='DB user')
parser.add_option('-w', '--db_pass', help='DB password')
parser.add_option('-o', '--output-file', help='output file')

options, args = parser.parse_args()

errors = []
error_msg = 'No %s specified. Use option %s'
if not options.db_name:
    errors.append(error_msg % ('database name', '-n'))
if not options.db_host:
    errors.append(error_msg % ('database host', '-H'))
if not options.db_user:
    errors.append(error_msg % ('database user', '-u'))
if not options.db_pass:
    errors.append(error_msg % ('database password', '-w'))
if not options.output_file:
    errors.append(error_msg % ('output file', '-o'))

if errors:
    print '\n'.join(errors)
    sys.exit(1)

您可以使用自定义操作来验证数据,如

import argparse
import re

class ValidateEmailAction(argparse.Action):
    ''' 
    Function will not validate domain names.
    e.g. abcd@abcd.abcd is valid here.
    '''
    def __call__(self, parser, namespace, values, option_string=None):

        super(argparse.Action, self).__call__(parser, namespace, values,
                                                  option_string=option_string)
        email = values
        pattern = "^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$"
        if not re.match(pattern, email) != None:
            raise AttributeError


parser = argparse.ArgumentParser()
parser.add_argument('-e', '--email', action=ValidateEmailAction, help='Enter valid email.')

同时检查供参考的自定义操作:
optpass
模块已折旧。从2.7开始,您可能需要使用
argparse
模块:Canu请为任何一个示例解释您试图如何使用它您运行脚本python blah.py-n dbname-H dbhost-p 8080-u dbuser-w dbpass-o path_to_文件,然后在代码中,您可以使用options.db_name(例如k)访问传递的值必须再传递一个参数。如何在代码中更改它?parser.add_option('-n'、'-db_name'、'var1',help='db name(如果有多个DBs,则用逗号分隔)…)调用parser.parse_args()后,额外的变量将在args变量中。parse_args()谢谢。这让我进展顺利……我只想说,您可以轻松打印
parser.format_help().strip()提供的帮助信息
然后使用
sys.exit(0)
退出以匹配本机函数。即使我输入了正确的电子邮件地址,您的代码也会抛出错误:
super(argparse.Action,self)。\u__(解析器、命名空间、值、属性错误:“超级”对象没有属性“\uuuu call\uuuuu”
这可能是新的更改。在检查
argparse.Action中的新更改后,我将向您进行更新