简体   繁体   English

如果python中没有选项,则选择工作

[英]optparse to to work if no options in python

I need to load the argument even if there is a option and if not a option. 即使没有选项,我也需要加载参数。

#!/usr/bin/python
import optparse

parser = optparse.OptionParser()
parser.add_option('-i', dest='name', help='some')
parser.add_option('-c', dest='name', help='some')
parser.add_option('-p', action='store', help='password')

print parser.parse_args()

[root@server tmp]# ./test -i abc
(<Values at 0x4011368: {'p': None, 'name': 'abc'}>, [])
[root@server tmp]# ./test  abc
(<Values at 0x5855368: {'p': None, 'name': None}>, ['abc'])

Now I need have the value "abc" even if I am not using any option. 现在,即使我没有使用任何选项,我都需要具有值“ abc”。 So please let know how can I access that value. 因此,请让我知道如何获取该价值。

Based solely on your output, you should be able to see that parse_args returns a tuple. 仅基于输出,您应该能够看到parse_args返回一个元组。 The first element of that tuple is an object containing values for defined options and the second element is a list of arguments leftover after parsing options. 该元组的第一个元素是一个对象,其中包含已定义选项的值,第二个元素是解析选项后剩余的参数列表。 You can read more about it in the official tutorial . 您可以在官方教程中了解更多信息。

Having this in mind, you can simply write 考虑到这一点,您可以简单地编写

options, arguments = parser.parse_args()

and use arguments to do whatever you want with that list. 并使用arguments对列表进行任何操作。

However, your problem seems to be that when you supply an option, argument is parsed as an option's value. 但是,您的问题似乎是当您提供一个选项时,参数被解析为一个选项的值。 This is caused by your way of defining options because options -i and -c need values. 这是由于您定义选项的方式引起的,因为选项-i-c需要值。

If you want those options to be boolean, you need to define that manually. 如果希望这些选项为布尔值,则需要手动定义。 Example for one option code would be something like 一个选项代码的示例类似于

# This defines an option which set name to True if option is provided, otherwise
# name is set to False
parser.add_option('-i', dest='name', help='some', action="store_true", default=False)

This would also mean that you don't need to provide value for that option, so argument won't be consumed when the parser reads options. 这也意味着您不需要为该选项提供值,因此解析器读取选项时不会消耗参数。

If you want your options to be non-boolean, but don't want to proved values for them, then I'm not sure I get what you're trying to do. 如果您希望选项为非布尔值,但又不想证明它们的值,那么我不确定我是否知道您要执行的操作。

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

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