有没有办法在Python中确定对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
Run Code Online (Sandbox Code Playgroud)
在使用之前如何判断是否a
具有该属性property
?
我一直在谷歌搜索近一个小时,我只是卡住了.
对于脚本stupidadder.py,它为命令arg添加2.
例如python stupidadder.py 4
打印6
python stupidadder.py 12
打印14
到目前为止我用谷歌搜索过:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('x', metavar='x', type=int, nargs='+',
help='input number')
...
args = parser.parse_args()
print args
x = args['x'] # fails here, not sure what to put
print x + 2
Run Code Online (Sandbox Code Playgroud)
我无法在任何地方找到直截了当的答案.文档太混乱了.:(有人可以帮忙吗?请和谢谢.:)
我正在使用argparse
模块来设置我的命令行选项.我也在dict
我的应用程序中使用a 作为配置.简单的键/值存储.
我正在寻找的是使用命令行参数覆盖JSON选项的可能性,而无需事先定义所有可能的参数.类似的东西--conf-key-1 value1 --conf-key-2 value2
,它会创建一个字典{'key_1': 'value1','key_2': 'value2'}
(参数中的' - '在字典中被'_'替换).然后我可以将这个dict与我的JSON配置(dict)结合起来.
所以基本上我想定义--conf-*
为一个参数,哪里*
可以是任何键,后面会是什么value
.
我确实找到了configargparse
模块,但据我所知,我从一个dict
已经使用过的开始.
我有什么想法可以解决这个问题?
我只是想知道是否有任何方法来编写python脚本来检查twitch.tv流是否存在?任何和所有的想法都表示赞赏!
编辑:我不知道为什么我的应用引擎标签被删除,但这将使用应用程序引擎.
我想parser.add_argument(...)
在我的代码中使用常量定义构建一个to map参数.
假设我有以下内容
import argparse
# Both are the same type
CONST_A = <something>
CONST_B = <otherthing>
parser = argparse.ArgumentParser()
parser.add_argument(...)
# I'd like the following to be true:
parser.parse_args("--foo A".split()).foo == CONST_A
parser.parse_args("--foo B".split()).foo == CONST_B
Run Code Online (Sandbox Code Playgroud)
我能代替...
什么呢?
我能做的最好的const
是:
import argparse
# Both are the same type
CONST_A = 10
CONST_B = 20
parser = argparse.ArgumentParser()
status_group = parser.add_mutually_exclusive_group(required=True)
status_group.add_argument("-a", const=CONST_A, action='store_const')
status_group.add_argument("-b", const=CONST_B, action='store_const')
# I'd like the following to be true:
print …
Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用两个子解析器来设置一个主解析器,这样当单独调用时,主解析器会显示一条帮助消息.
def help_message():
print "help message"
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='sp')
parser_a = subparsers.add_parser('a')
parser_a.required = False
#some options...
parser_b = subparsers.add_parser('b')
parser_b.required = False
#some options....
args = parser.parse_args([])
if args.sp is None:
help_message()
elif args.sp == 'a':
print "a"
elif args.sp == 'b':
print "b"
Run Code Online (Sandbox Code Playgroud)
这段代码在Python 3上运行良好,我希望它能在Python 2.x上运行
运行'python myprogram.py'时我得到了这个
myprogram.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)
这是我的问题:我如何设法在shell中编写'python myprogram.py'并获取帮助消息而不是错误.
python ×6
argparse ×3
python-2.7 ×2
args ×1
arguments ×1
attributes ×1
parsing ×1
twitch ×1
web ×1