我对Python很陌生,并希望在我正在编写的应用程序中保留所有内容为“Pythonic”。
我正在使用docopt,它允许我在Usage
部分的程序顶部定义命令行参数和结构。所有参数都保存在字典中。
然后我需要弄清楚用户想要做什么以及他们为操作提供了哪些参数或选项。
以下是一些示例代码:
""" Test program
Usage:
plci.py move (user) <id> <source> <destination>
plci.py remove user (--id=TARGET|--username=TARGET) <source_account>
"""
import requests
import sys
import os.path
try: import simplejson as json
except ImportError: import json
import user_operations
import ConfigParser
from docopt import docopt
import recovery
if __name__ == '__main__':
config = ConfigParser.ConfigParser()
config.read("pcli.sysconf")
#Headers
headers = {'Content-Type':'application/json','Accept':'application/json'}
#Config variables
appid = config.get("Config", "appid")
api_root = config.get("Config", "api_root")
secret = config.get("Config", "secret")
auto_recovery = config.getboolean("Config", "auto_recovery")
token_duration = config.get("Config", "token_duration")
arguments = docopt(__doc__, version='1.0.0rc2')
print(arguments)
token, scope = user_operations.get_auth_token_and_scope(api_root, appid, secret, token_duration, headers)
if arguments['remove']:
if arguments['user']:
if arguments['--id'] is not None:
print "YAY, now we know that we want to remove a user being identified by their id num which is " + arguments['--id']
if arguments['--username'] is not None:
print "YAY, now we know that we want to remove a user being identified by their username which is " + arguments['--username']
输入的位置如下:
remove user 10 --username=testuser01
输出结果如下:
{'--id': None,
'--username': 'testuser01',
'<destination>': None,
'<id>': None,
'<source>': None,
'<source_account>': '10',
'move': False,
'remove': True,
'user': True}
YAY, now we know that we want to remove a user being identified by their username which is testuser01
是否有其他/更好的方式来查看arguments
字典并选择适当的函数?
修改
if arguments['remove'] and arguments['user'] and arguments['--id']:
print "YAY, now we know that we want to remove a user being identified by their id num which is " + arguments['--id']
if arguments['remove'] and arguments['user'] and arguments['--username']:
print "YAY, now we know that we want to remove a user being identified by their username which is " + arguments['--username']
我有这个,但仍然有很多代码重复...