简体   繁体   English

Python getopt参数过多

[英]Python getopt too many arguments

I am at a dead end. 我死定了。 I am trying to pass arguments into a Linux to run certain operations. 我试图将参数传递给Linux以运行某些操作。 I want to avoid the user from entering too many paramters. 我想避免用户输入太多参数。

For example the desired running of the script would be as such: 例如,脚本的期望运行将是这样的:

./audit.py -a

I want to prevent the following: 我要防止以下情况:

./audit.py -af

This seems to be running whatever is specified for 'a' and then 'f'. 无论为“ a”然后是“ f”指定了什么,这似乎都在运行。 In this case if it is like '-af' then I need it to quit with a sys.exit(). 在这种情况下,如果它像“ -af”,则需要使用sys.exit()退出。 My len(sys.argv[1:]) always produces a result of 1 no matter how parameters I put in. 无论我输入的参数如何,我的len(sys.argv [1:])总是产生1的结果。

import getopts
import sys
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'v:adfh')
    except getopt.GetoptError as err:
        sys.exit(str(err))
    if len(sys.argv[1:]) != 1:
        sys.exit('Invalid')

    for o,a in opts:
        if o in ('-v', '--volume'):
            print 'Volumes'
        elif len(sys.argv[2:]) != 0:
            sys.exit('Too many arguments')
        elif o in ('-a', '--agent'):
            print 'Full audit of agents only'
        elif o in ('-d', '--device'):
            print 'Full audit of device only'
        elif o in ('-f', '--full'):
            print 'Full audit of device/agents'
        elif o in ('-h', '--help'):
            sys.exit('Help Section')
if __name__ == '__main__':
    main()

The value of sys.argv[1:] is ['-af'] and if you will check for lenght of ['-af'] is 1 which is why if len(sys.argv[1:]) != 1: is always false. sys.argv[1:] is ['-af'] ,如果要检查['-af']的长度为1,这就是if len(sys.argv[1:]) != 1:始终为假。 Instead if you want to check the length of first argument either you need to use len(sys.argv[1:][0]) or else for each of the arguments lengths. 相反,如果要检查第一个参数的长度,则需要使用len(sys.argv[1:][0])或其他每个参数的长度。

The problem is that sys.argv[1:] produces a slice . 问题是sys.argv[1:]产生slice In other words, it's a list. 换句话说,它是一个列表。 In your case, it's something like ['-af'] . 在您的情况下,它类似于['-af'] So of course, the length will always be 1 except if you passed no parameters. 因此,当然,该长度将始终为1除非您未传递任何参数。 Perhaps you meant to do this: 也许您打算这样做:

if not all(i < 1 for i in sys.argv[1:]):
    sys.exit('Invalid')

You are looking at option clustering. 您正在查看选项群集。 There does not seem to be any facility in getopt to disable this feature. getopt中似乎没有任何功能可以禁用此功能。 However, you probably shouldn't be using this package, anyway. 但是,无论如何,您可能不应该使用此软件包。 Would argparse perhaps be more suitable for your needs? argparse也许会更适合您的需求?

Not a full answer but you might be glad to look at a library I was very happy to find. 没有一个完整的答案,但是您可能很高兴看到我很高兴找到的图书馆。

docopts - there is a great video describing how to use docopts-精彩的视频介绍了如何使用

This is a great tool, you just describe your arguments in the module document section, eg; 这是一个很棒的工具,您只需在模块文档部分中描述您的参数即可。

'''
Usage:
   myprog -a -v <volumes>...
   myprog -f
   myprog -h | --help
'''
import docopt
args=docopt.docopt(__doc__)

This will produce the following dictionary if run as myprog -a -v one two three ; 如果以myprog -a -v one two three运行,则将生成以下字典;

{
  "--help": false, 
  "-a": true, 
  "-f": false, 
  "-h": false, 
  "-v": true, 
  "": [
    "myprog", 
    "one", 
    "two", 
    "three"
  ]
}

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

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