python 避免多重条件嵌套_在python中避免嵌套条件

我对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']

我有这个,但仍然有很多代码重复。。。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值