python调用什么函数实现对文件内容的读取_Python 类似switch/case语句实现方法 获取文件内容匹配函数并执行 字符串拼接...

这个主要提供了一种思路,这个不太好理解,我彻底敲了一遍,心里有点低。参考下面的文章

标题:Python switch/case语句实现方法

来源:https://blog.csdn.net/l460133921/article/details/74892476

与Java、C\C++等语言不同,Python中是不提供switch/case语句的,这一点让我感觉到很奇怪。我们可以通过如下几种方法来实现switch/case语句。

使用if…elif…elif…else 实现switch/case

可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。

使用字典 实现switch/case

可以使用字典实现switch/case这种方式易维护,同时也能够减少代码量。如下是使用字典模拟的switch/case实现:

#!/usr/bin/python

# -*- coding: utf-8 -*-

def zkper(msg):

print msg

print ("zkper函数")

def scp(msg):

print msg

print ("scp函数")

def cou(msg):

print msg

print ("cou函数")

def error(msg):

print msg

print ("error函数")

def other(msg):

print msg

print (msg+"不更新")

def notify_result(num, msg):

numbers = {

'zkper=1' : zkper,

'scp=1' : scp,

'cou=1' : cou,

3 : error

}

method = numbers.get(num, other)

if method:

method(msg)

def update_all_aw():

for line in open("upmips.cfg"):

a=line.strip()

# print(a)

if __name__ == "__main__":

notify_result(a, a)

print ("===")

update_all_aw()

umpips.cfg的内容为

zkper=1

scp=1

cou=0

bjs=0

输出如下内容:

zkper=1

zkper函数

===

scp=1

scp函数

===

cou=0

cou=0不更新

===

bjs=0

bjs=0不更新

===

上面设计思路,=1的更新该函数,=0表示不更新。

里面使用了逐行读取配合字典函数来达到效果。

因后续添加需要函数传参,所以对上面的逻辑进行修改,

配置文件添加了包名,通过split函数进行字符串切割输出

函数原文如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

def zkper(msg):

print msg

print ("执行zkper函数")

def scp(msg):

print msg

print ("执行scp函数")

def cou(msg):

print msg

print ("执行cou函数")

def error(msg):

print msg

print ("执行error函数")

def other(msg):

print msg

print (msg+"该应用不更新")

def notify_result(num, msg):

# 匹配字符串名,'scp=1'匹配下面传入参数名,'scp'匹配上面函数执行

numbers = {

'zkper=1' : zkper,

'scp=1' : scp,

'cou=1' : cou,

3 : error

}

# 上面函数没有可匹配名,就执行上面other函数,msg为传入参数

method = numbers.get(num, other)

if method:

method(msg)

def update_all_aw():

for line in open("upmips.cfg"):

# 更新配置文件逐行

upconf=line.strip()

# 更新函数

upfunc=upconf.split('#',1)[0]

# 更新包

uppack=upconf.split('#',1)[1]

if __name__ == "__main__":

notify_result(upfunc, uppack)

print ("==================")

update_all_aw()

配置文件:upmips.cfg

zkper=1#mips_zkper-1.8.1-bin.tar.gz

scp=1#mips_scp-1.8.1-bin.tar.gz

cou=0#cou=0

bjs=0#bjs=0

下面为执行结果:

执行zkper函数

==================

mips_scp-1.8.1-bin.tar.gz

执行scp函数

==================

cou=0

cou=0该应用不更新

==================

bjs=0

bjs=0该应用不更新

==================

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值