我对Python还很陌生,希望在我编写的应用程序中尽可能保持一切“Pythonic”。在
我使用的是docopt,它允许我在程序顶部的Usage部分定义命令行参数和结构。所有的参数都保存在字典中。在
然后我需要准确地整理出用户想要做什么,以及他们为操作提供了哪些参数或选项。在
下面是一些示例代码:""" Test program
Usage:
plci.py move (user)
plci.py remove user (--id=TARGET|--username=TARGET)
"""
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']
输入如下:
^{pr2}$
结果如下:{'--id': None,
'--username': 'testuser01',
'': None,
'': None,
'': None,
'': '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']
我有这个,但仍然有很多代码重复。。。在