python执行js语句,无函数返回值

李魔佛 发表了文章 • 0 个评论 • 22 次浏览 • 2020-11-30 16:11 • 来自相关话题

有时候在JS代码里面抠出部分语句,但是不是一个函数。
如下面的一段JSvar radra27radra27 = "D";
var ra72419ra91ra72419ra91 = "7.241.9" + ".";
var raurst500ra63raurst500ra63 = "urst=500";
var ravalidtora49ravalidtora49 = "validto=";
var raevphncdra57raevphncdra57 = "ev.ph" + "ncd";
var ra16067161ra17ra16067161ra17 = "16067161";
var radeos202ra16radeos202ra16 = "deos/20" + "2";
var ra1080p4ra73ra1080p4ra73 = "/1080P_4";
var ra209hashra72ra209hashra72 = "209&hash";
var ra2bmkdz7nra36ra2bmkdz7nra36 = "2BMKd" + "z7N";
var ra6708909ra29ra6708909ra29 = "6708909" + "&";
var ra00kip4ra41ra00kip4ra41 = "00k&i" + "p=4";
var ra006163ra73ra006163ra73 = "006/16/" + "3";
var raro7upu3ra66raro7upu3ra66 = "Ro7UPU%3";
var raroiu6qra26raroiu6qra26 = "=rOiU6q%";
var ra075351mra26ra075351mra26 = "075351." + "m";
var ramgdmctbvra11ramgdmctbvra11 = "MgdmCtbV";
var rap4validra25rap4validra25 = "p4?valid";
var ra09ratera79ra09ratera79 = "09&rate=";
var rancomvira35rancomvira35 = "n.com/vi";
var ra24075351ra94ra24075351ra94 = "24075" + "351";
var ra000k324ra70ra000k324ra70 = "000K_324";
var ra50000kbra49ra50000kbra49 = "50000k&" + "b";
var rahttpsra83rahttpsra83 = "https://";
var rafrom160ra56rafrom160ra56 = "from=16" + "0";
var quality_1080p =/* + radra27radra27 + */rahttpsra83rahttpsra83 + /* + rancomvira35rancomvira35 + */raevphncdra57raevphncdra57 + /* + radra27radra27 + */rancomvira35rancomvira35 + /* + ra006163ra73ra006163ra73 + */radeos202ra16radeos202ra16 + /* + ra09ratera79ra09ratera79 + */ra006163ra73ra006163ra73 + /* + ra1080p4ra73ra1080p4ra73 + */ra24075351ra94ra24075351ra94 + /* + raroiu6qra26raroiu6qra26 + */ra1080p4ra73ra1080p4ra73 + /* + ra000k324ra70ra000k324ra70 + */ra000k324ra70ra000k324ra70 + /* + rancomvira35rancomvira35 + */ra075351mra26ra075351mra26 + /* + ravalidtora49ravalidtora49 + */rap4validra25rap4validra25 + /* + ra209hashra72ra209hashra72 + */rafrom160ra56rafrom160ra56 + /* + ra1080p4ra73ra1080p4ra73 + */ra6708909ra29ra6708909ra29 + /* + ra209hashra72ra209hashra72 + */ravalidtora49ravalidtora49 + /* + ramgdmctbvra11ramgdmctbvra11 + */ra16067161ra17ra16067161ra17 + /* + ra24075351ra94ra24075351ra94 + */ra09ratera79ra09ratera79 + /* + ra50000kbra49ra50000kbra49 + */ra50000kbra49ra50000kbra49 + /* + ramgdmctbvra11ramgdmctbvra11 + */raurst500ra63raurst500ra63 + /* + ra209hashra72ra209hashra72 + */ra00kip4ra41ra00kip4ra41 + /* + raroiu6qra26raroiu6qra26 + */ra72419ra91ra72419ra91 + /* + ra09ratera79ra09ratera79 + */ra209hashra72ra209hashra72 + /* + raro7upu3ra66raro7upu3ra66 + */raroiu6qra26raroiu6qra26 + /* + ra075351mra26ra075351mra26 + */ra2bmkdz7nra36ra2bmkdz7nra36 + /* + ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;
做了很多的运算,掩人耳目,虽然看多几下,用python写也简单,或者把它放入一个function里面也可以。
比如实时网络上下载获取一段js,然后再在头部和尾部组装为function。
function getValue(){
xxxxxx
xxxxxx
return flashvars_324075351
}
 
然后执行这一段JS,call返回函数 getValue() 就可以拿到返回值了。
 
不过今天我们用其他的方法直接获取flashvars_324075351
 
使用jsp库即可。
 
把上面的JS语句var radra27radra27 = "D";
var ra72419ra91ra72419ra91 = "7.241.9" + ".";
var raurst500ra63raurst500ra63 = "urst=500";
var ravalidtora49ravalidtora49 = "validto=";
var raevphncdra57raevphncdra57 = "ev.ph" + "ncd";
var ra16067161ra17ra16067161ra17 = "16067161";
var radeos202ra16radeos202ra16 = "deos/20" + "2";
var ra1080p4ra73ra1080p4ra73 = "/1080P_4";
var ra209hashra72ra209hashra72 = "209&hash";
var ra2bmkdz7nra36ra2bmkdz7nra36 = "2BMKd" + "z7N";
var ra6708909ra29ra6708909ra29 = "6708909" + "&";
var ra00kip4ra41ra00kip4ra41 = "00k&i" + "p=4";
var ra006163ra73ra006163ra73 = "006/16/" + "3";
var raro7upu3ra66raro7upu3ra66 = "Ro7UPU%3";
var raroiu6qra26raroiu6qra26 = "=rOiU6q%";
var ra075351mra26ra075351mra26 = "075351." + "m";
var ramgdmctbvra11ramgdmctbvra11 = "MgdmCtbV";
var rap4validra25rap4validra25 = "p4?valid";
var ra09ratera79ra09ratera79 = "09&rate=";
var rancomvira35rancomvira35 = "n.com/vi";
var ra24075351ra94ra24075351ra94 = "24075" + "351";
var ra000k324ra70ra000k324ra70 = "000K_324";
var ra50000kbra49ra50000kbra49 = "50000k&" + "b";
var rahttpsra83rahttpsra83 = "https://";
var rafrom160ra56rafrom160ra56 = "from=16" + "0";
var quality_1080p =/* + radra27radra27 + */rahttpsra83rahttpsra83 + /* + rancomvira35rancomvira35 + */raevphncdra57raevphncdra57 + /* + radra27radra27 + */rancomvira35rancomvira35 + /* + ra006163ra73ra006163ra73 + */radeos202ra16radeos202ra16 + /* + ra09ratera79ra09ratera79 + */ra006163ra73ra006163ra73 + /* + ra1080p4ra73ra1080p4ra73 + */ra24075351ra94ra24075351ra94 + /* + raroiu6qra26raroiu6qra26 + */ra1080p4ra73ra1080p4ra73 + /* + ra000k324ra70ra000k324ra70 + */ra000k324ra70ra000k324ra70 + /* + rancomvira35rancomvira35 + */ra075351mra26ra075351mra26 + /* + ravalidtora49ravalidtora49 + */rap4validra25rap4validra25 + /* + ra209hashra72ra209hashra72 + */rafrom160ra56rafrom160ra56 + /* + ra1080p4ra73ra1080p4ra73 + */ra6708909ra29ra6708909ra29 + /* + ra209hashra72ra209hashra72 + */ravalidtora49ravalidtora49 + /* + ramgdmctbvra11ramgdmctbvra11 + */ra16067161ra17ra16067161ra17 + /* + ra24075351ra94ra24075351ra94 + */ra09ratera79ra09ratera79 + /* + ra50000kbra49ra50000kbra49 + */ra50000kbra49ra50000kbra49 + /* + ramgdmctbvra11ramgdmctbvra11 + */raurst500ra63raurst500ra63 + /* + ra209hashra72ra209hashra72 + */ra00kip4ra41ra00kip4ra41 + /* + raroiu6qra26raroiu6qra26 + */ra72419ra91ra72419ra91 + /* + ra09ratera79ra09ratera79 + */ra209hashra72ra209hashra72 + /* + raro7upu3ra66raro7upu3ra66 + */raroiu6qra26raroiu6qra26 + /* + ra075351mra26ra075351mra26 + */ra2bmkdz7nra36ra2bmkdz7nra36 + /* + ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;
后面加一个返回值,但不需要加return
比如....
ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;
flashvars_324075351;
然后直接调用jspy
res = js2py.eval_js(js)
 
执行后print(res) , 显示的值就是flashvars_324075351
原创文章,转载请注明出处
http://30daydo.com/article/44112
  查看全部
有时候在JS代码里面抠出部分语句,但是不是一个函数。
如下面的一段JS
var radra27radra27 = "D";
var ra72419ra91ra72419ra91 = "7.241.9" + ".";
var raurst500ra63raurst500ra63 = "urst=500";
var ravalidtora49ravalidtora49 = "validto=";
var raevphncdra57raevphncdra57 = "ev.ph" + "ncd";
var ra16067161ra17ra16067161ra17 = "16067161";
var radeos202ra16radeos202ra16 = "deos/20" + "2";
var ra1080p4ra73ra1080p4ra73 = "/1080P_4";
var ra209hashra72ra209hashra72 = "209&hash";
var ra2bmkdz7nra36ra2bmkdz7nra36 = "2BMKd" + "z7N";
var ra6708909ra29ra6708909ra29 = "6708909" + "&";
var ra00kip4ra41ra00kip4ra41 = "00k&i" + "p=4";
var ra006163ra73ra006163ra73 = "006/16/" + "3";
var raro7upu3ra66raro7upu3ra66 = "Ro7UPU%3";
var raroiu6qra26raroiu6qra26 = "=rOiU6q%";
var ra075351mra26ra075351mra26 = "075351." + "m";
var ramgdmctbvra11ramgdmctbvra11 = "MgdmCtbV";
var rap4validra25rap4validra25 = "p4?valid";
var ra09ratera79ra09ratera79 = "09&rate=";
var rancomvira35rancomvira35 = "n.com/vi";
var ra24075351ra94ra24075351ra94 = "24075" + "351";
var ra000k324ra70ra000k324ra70 = "000K_324";
var ra50000kbra49ra50000kbra49 = "50000k&" + "b";
var rahttpsra83rahttpsra83 = "https://";
var rafrom160ra56rafrom160ra56 = "from=16" + "0";
var quality_1080p =/* + radra27radra27 + */rahttpsra83rahttpsra83 + /* + rancomvira35rancomvira35 + */raevphncdra57raevphncdra57 + /* + radra27radra27 + */rancomvira35rancomvira35 + /* + ra006163ra73ra006163ra73 + */radeos202ra16radeos202ra16 + /* + ra09ratera79ra09ratera79 + */ra006163ra73ra006163ra73 + /* + ra1080p4ra73ra1080p4ra73 + */ra24075351ra94ra24075351ra94 + /* + raroiu6qra26raroiu6qra26 + */ra1080p4ra73ra1080p4ra73 + /* + ra000k324ra70ra000k324ra70 + */ra000k324ra70ra000k324ra70 + /* + rancomvira35rancomvira35 + */ra075351mra26ra075351mra26 + /* + ravalidtora49ravalidtora49 + */rap4validra25rap4validra25 + /* + ra209hashra72ra209hashra72 + */rafrom160ra56rafrom160ra56 + /* + ra1080p4ra73ra1080p4ra73 + */ra6708909ra29ra6708909ra29 + /* + ra209hashra72ra209hashra72 + */ravalidtora49ravalidtora49 + /* + ramgdmctbvra11ramgdmctbvra11 + */ra16067161ra17ra16067161ra17 + /* + ra24075351ra94ra24075351ra94 + */ra09ratera79ra09ratera79 + /* + ra50000kbra49ra50000kbra49 + */ra50000kbra49ra50000kbra49 + /* + ramgdmctbvra11ramgdmctbvra11 + */raurst500ra63raurst500ra63 + /* + ra209hashra72ra209hashra72 + */ra00kip4ra41ra00kip4ra41 + /* + raroiu6qra26raroiu6qra26 + */ra72419ra91ra72419ra91 + /* + ra09ratera79ra09ratera79 + */ra209hashra72ra209hashra72 + /* + raro7upu3ra66raro7upu3ra66 + */raroiu6qra26raroiu6qra26 + /* + ra075351mra26ra075351mra26 + */ra2bmkdz7nra36ra2bmkdz7nra36 + /* + ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;

做了很多的运算,掩人耳目,虽然看多几下,用python写也简单,或者把它放入一个function里面也可以。
比如实时网络上下载获取一段js,然后再在头部和尾部组装为function。
function getValue(){
xxxxxx
xxxxxx
return flashvars_324075351
}
 
然后执行这一段JS,call返回函数 getValue() 就可以拿到返回值了。
 
不过今天我们用其他的方法直接获取flashvars_324075351
 
使用jsp库即可。
 
把上面的JS语句
var radra27radra27 = "D";
var ra72419ra91ra72419ra91 = "7.241.9" + ".";
var raurst500ra63raurst500ra63 = "urst=500";
var ravalidtora49ravalidtora49 = "validto=";
var raevphncdra57raevphncdra57 = "ev.ph" + "ncd";
var ra16067161ra17ra16067161ra17 = "16067161";
var radeos202ra16radeos202ra16 = "deos/20" + "2";
var ra1080p4ra73ra1080p4ra73 = "/1080P_4";
var ra209hashra72ra209hashra72 = "209&hash";
var ra2bmkdz7nra36ra2bmkdz7nra36 = "2BMKd" + "z7N";
var ra6708909ra29ra6708909ra29 = "6708909" + "&";
var ra00kip4ra41ra00kip4ra41 = "00k&i" + "p=4";
var ra006163ra73ra006163ra73 = "006/16/" + "3";
var raro7upu3ra66raro7upu3ra66 = "Ro7UPU%3";
var raroiu6qra26raroiu6qra26 = "=rOiU6q%";
var ra075351mra26ra075351mra26 = "075351." + "m";
var ramgdmctbvra11ramgdmctbvra11 = "MgdmCtbV";
var rap4validra25rap4validra25 = "p4?valid";
var ra09ratera79ra09ratera79 = "09&rate=";
var rancomvira35rancomvira35 = "n.com/vi";
var ra24075351ra94ra24075351ra94 = "24075" + "351";
var ra000k324ra70ra000k324ra70 = "000K_324";
var ra50000kbra49ra50000kbra49 = "50000k&" + "b";
var rahttpsra83rahttpsra83 = "https://";
var rafrom160ra56rafrom160ra56 = "from=16" + "0";
var quality_1080p =/* + radra27radra27 + */rahttpsra83rahttpsra83 + /* + rancomvira35rancomvira35 + */raevphncdra57raevphncdra57 + /* + radra27radra27 + */rancomvira35rancomvira35 + /* + ra006163ra73ra006163ra73 + */radeos202ra16radeos202ra16 + /* + ra09ratera79ra09ratera79 + */ra006163ra73ra006163ra73 + /* + ra1080p4ra73ra1080p4ra73 + */ra24075351ra94ra24075351ra94 + /* + raroiu6qra26raroiu6qra26 + */ra1080p4ra73ra1080p4ra73 + /* + ra000k324ra70ra000k324ra70 + */ra000k324ra70ra000k324ra70 + /* + rancomvira35rancomvira35 + */ra075351mra26ra075351mra26 + /* + ravalidtora49ravalidtora49 + */rap4validra25rap4validra25 + /* + ra209hashra72ra209hashra72 + */rafrom160ra56rafrom160ra56 + /* + ra1080p4ra73ra1080p4ra73 + */ra6708909ra29ra6708909ra29 + /* + ra209hashra72ra209hashra72 + */ravalidtora49ravalidtora49 + /* + ramgdmctbvra11ramgdmctbvra11 + */ra16067161ra17ra16067161ra17 + /* + ra24075351ra94ra24075351ra94 + */ra09ratera79ra09ratera79 + /* + ra50000kbra49ra50000kbra49 + */ra50000kbra49ra50000kbra49 + /* + ramgdmctbvra11ramgdmctbvra11 + */raurst500ra63raurst500ra63 + /* + ra209hashra72ra209hashra72 + */ra00kip4ra41ra00kip4ra41 + /* + raroiu6qra26raroiu6qra26 + */ra72419ra91ra72419ra91 + /* + ra09ratera79ra09ratera79 + */ra209hashra72ra209hashra72 + /* + raro7upu3ra66raro7upu3ra66 + */raroiu6qra26raroiu6qra26 + /* + ra075351mra26ra075351mra26 + */ra2bmkdz7nra36ra2bmkdz7nra36 + /* + ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;

后面加一个返回值,但不需要加return
比如
....
ra50000kbra49ra50000kbra49 + */ramgdmctbvra11ramgdmctbvra11 + /* + radeos202ra16radeos202ra16 + */raro7upu3ra66raro7upu3ra66 + /* + ra075351mra26ra075351mra26 + */radra27radra27;
flashvars_324075351["quality_1080p"] = quality_1080p;
flashvars_324075351;

然后直接调用jspy
res = js2py.eval_js(js)
 
执行后print(res) , 显示的值就是flashvars_324075351
原创文章,转载请注明出处
http://30daydo.com/article/44112
 

python多重继承的super调用父类的兄弟类

李魔佛 发表了文章 • 0 个评论 • 58 次浏览 • 2020-11-26 19:04 • 来自相关话题

先看一段代码:class A:
def __init__(self):
print('A init')
print(self)


class B:
def __init__(self):
print('B init')
print(self)


class C:
def __init__(self):
print('C init')
print(self)


class D(C, B, A):
def __init__(self):
super(A, self).__init__()
super(C, self).__init__()
super(B, self).__init__()
print('D ')


def main():
d = D()
看输出的是什么:B init
<__main__.D object at 0x00000000026365B0>
A init
<__main__.D object at 0x00000000026365B0>
D init-
为什么不输出C init ?
 
那么这个药从super的函数实现说起:def super(class, obj):
mro_list = obj.__class__.mro()
next_parent_class = mro_list[mro_list.index(class)+1]
return next_parent_class
super函数中,mro_list得到的是类的mro列表,mro列表就是类的继承有序关系图
比如上面代码中 
C, B, A 在D中的mro是下面这样的。[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]




你提供的类名class传入来后,比如是C,那么找到C所在的index,然后加1后的class,也就是B,所以super(C,self).__init__() 
实际调用的是B.__init__()
 
 
另外,如果在多重继承中,要调用父类的父类的父类。。。。,
可以直接用改类的类名就可以# 多重继承


class A:
def __init__(self):
print('A init')
print(self)

def fun(self):
print('A',self)

class B(A):
def __init__(self):
print('B init')
print(self)

def fun(self):
print('B', self)


class C(B):

def __init__(self):
print('C init')
print(self)

def fun(self):
print('C', self)

class X:

def fun(self):
print('X',self)

class D(C):
def __init__(self):
# super(B, self).__init__() # super(D) -> 指向了C
print('D init')

def fun(self):
C.fun(self)
B.fun(self)
A.fun(self)
X.fun(self)



def main():
d = D()
print(d.__class__.mro())
d.fun()

if __name__ == '__main__':
main()
 
结果:D init
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
C <__main__.D object at 0x00000000025F6700>
B <__main__.D object at 0x00000000025F6700>
A <__main__.D object at 0x00000000025F6700>
X <__main__.D object at 0x00000000025F6700>
其实super和父类子类没什么关系, super关系的是mro里面的顺序。

 原文链接:http://30daydo.com/article/44107 
转载请注明出处
  查看全部
先看一段代码:
class A:
def __init__(self):
print('A init')
print(self)


class B:
def __init__(self):
print('B init')
print(self)


class C:
def __init__(self):
print('C init')
print(self)


class D(C, B, A):
def __init__(self):
super(A, self).__init__()
super(C, self).__init__()
super(B, self).__init__()
print('D ')


def main():
d = D()

看输出的是什么:
B init
<__main__.D object at 0x00000000026365B0>
A init
<__main__.D object at 0x00000000026365B0>
D init-

为什么不输出C init ?
 
那么这个药从super的函数实现说起:
def super(class, obj):
mro_list = obj.__class__.mro()
next_parent_class = mro_list[mro_list.index(class)+1]
return next_parent_class

super函数中,mro_list得到的是类的mro列表,mro列表就是类的继承有序关系图
比如上面代码中 
C, B, A 在D中的mro是下面这样的。
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]




你提供的类名class传入来后,比如是C,那么找到C所在的index,然后加1后的class,也就是B,所以super(C,self).__init__() 
实际调用的是B.__init__()
 
 
另外,如果在多重继承中,要调用父类的父类的父类。。。。,
可以直接用改类的类名就可以
# 多重继承


class A:
def __init__(self):
print('A init')
print(self)

def fun(self):
print('A',self)

class B(A):
def __init__(self):
print('B init')
print(self)

def fun(self):
print('B', self)


class C(B):

def __init__(self):
print('C init')
print(self)

def fun(self):
print('C', self)

class X:

def fun(self):
print('X',self)

class D(C):
def __init__(self):
# super(B, self).__init__() # super(D) -> 指向了C
print('D init')

def fun(self):
C.fun(self)
B.fun(self)
A.fun(self)
X.fun(self)



def main():
d = D()
print(d.__class__.mro())
d.fun()

if __name__ == '__main__':
main()

 
结果:
D init
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
C <__main__.D object at 0x00000000025F6700>
B <__main__.D object at 0x00000000025F6700>
A <__main__.D object at 0x00000000025F6700>
X <__main__.D object at 0x00000000025F6700>

其实super和父类子类没什么关系, super关系的是mro里面的顺序。

 原文链接:http://30daydo.com/article/44107 
转载请注明出处
 

python pathspec 库的作用

李魔佛 发表了文章 • 0 个评论 • 53 次浏览 • 2020-11-25 13:28 • 来自相关话题

作为路径匹配用的。
 
看以下实例:
def get_ignore_matches():
# 排除文件
global ignore_matches
ignore_file = os.path.join(os.path.abspath(os.curdir), '.gitignore')
if not os.path.exists(ignore_file):
return None
if ignore_matches is not None:
return ignore_matches
with open(ignore_file, 'r') as fh:
spec = pathspec.PathSpec.from_lines('gitwildmatch', fh)
ignore_matches = spec
return ignore_matches


def is_ignored(file_name: str) -> bool:
# 匹配就ignore
matches = get_ignore_matches()
if matches is None:
return False
return matches.match_file(file_name)

gitignore文件里面的内容就会被匹配到
.idea/
build/
dist/
venv/
*.pyc
__pycache__/
*.egg-info/
tmp/ 查看全部
作为路径匹配用的。
 
看以下实例:
def get_ignore_matches():
# 排除文件
global ignore_matches
ignore_file = os.path.join(os.path.abspath(os.curdir), '.gitignore')
if not os.path.exists(ignore_file):
return None
if ignore_matches is not None:
return ignore_matches
with open(ignore_file, 'r') as fh:
spec = pathspec.PathSpec.from_lines('gitwildmatch', fh)
ignore_matches = spec
return ignore_matches


def is_ignored(file_name: str) -> bool:
# 匹配就ignore
matches = get_ignore_matches()
if matches is None:
return False
return matches.match_file(file_name)

gitignore文件里面的内容就会被匹配到
.idea/
build/
dist/
venv/
*.pyc
__pycache__/
*.egg-info/
tmp/

夜深了,你们还在吗?

chenchen 发表了文章 • 0 个评论 • 60 次浏览 • 2020-11-20 22:34 • 来自相关话题

夜深了,你们还在吗???????????????????
夜深了,你们还在吗???????????????????

大家好啊,日常报道,关照关照

chenchen 发表了文章 • 0 个评论 • 63 次浏览 • 2020-11-20 17:11 • 来自相关话题

大家好啊,日常报道,关照关照。。。。。。。。。。。。
大家好啊,日常报道,关照关照。。。。。。。。。。。。

异步asyncio加锁 的正确用法

李魔佛 发表了文章 • 0 个评论 • 100 次浏览 • 2020-11-15 10:19 • 来自相关话题

对于全局变量count进行统计加锁
import aiohttp
import asyncio
import execjs
import threading
global pages
global count

headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "dcfm.eastmoney.com",
"Pragma": "no-cache",
"Referer": "http://data.eastmoney.com/xg/xg/default.html",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/69.0.3497.81 Chrome/69.0.3497.81 Safari/537.36",
}

home_url = 'http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=XGSG_LB&token=70f12f2f4f091e459a279469fe49eca5&st=purchasedate,securitycode&sr=-1&p={}&ps=50&js=var%20hsEnHLwG={{pages:(tp),data:(x)}}&rt=53512217'

loop = asyncio.get_event_loop()
# lock = threading.Lock()
lock = asyncio.Lock()
def parse_json(content):
content += ';function getV(){return hsEnHLwG;}'
ctx = execjs.compile(content)
result = ctx.call('getV')
return result


async def fetch(session,page):
global pages
global count
async with session.get(home_url.format(page),headers=headers) as resp:
# print(f'here:: {page}')
content = await resp.text()

try:
js_content = parse_json(content)
for stock_info in js_content['data']:
securityshortname = stock_info['securityshortname']
# print(securityshortname)
except Exception as e:
print(e)

async with lock:
count=count+1

print(f'count:{count}')
if count == pages:
print('End of loop')
loop.stop()



async def main():
global pages
global count
count=0
async with aiohttp.ClientSession() as session:
async with session.get(home_url.format(1), headers=headers) as resp:

content = await resp.text()
js_data = parse_json(content)
pages = js_data['pages']
print(f'pages: {pages}')
for page in range(1,pages+1):
task = asyncio.ensure_future(fetch(session,page))

await asyncio.sleep(1)


asyncio.ensure_future(main())
loop.run_forever()
1. 如果不加入锁,每次运行的结果可能不一样。
2. 不能用多线程的threading 锁,得到的每次运行结果也有可能不一样
3. 用asyncio的锁要 加关键字 async
  查看全部
对于全局变量count进行统计加锁
import aiohttp
import asyncio
import execjs
import threading
global pages
global count

headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "dcfm.eastmoney.com",
"Pragma": "no-cache",
"Referer": "http://data.eastmoney.com/xg/xg/default.html",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/69.0.3497.81 Chrome/69.0.3497.81 Safari/537.36",
}

home_url = 'http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=XGSG_LB&token=70f12f2f4f091e459a279469fe49eca5&st=purchasedate,securitycode&sr=-1&p={}&ps=50&js=var%20hsEnHLwG={{pages:(tp),data:(x)}}&rt=53512217'

loop = asyncio.get_event_loop()
# lock = threading.Lock()
lock = asyncio.Lock()
def parse_json(content):
content += ';function getV(){return hsEnHLwG;}'
ctx = execjs.compile(content)
result = ctx.call('getV')
return result


async def fetch(session,page):
global pages
global count
async with session.get(home_url.format(page),headers=headers) as resp:
# print(f'here:: {page}')
content = await resp.text()

try:
js_content = parse_json(content)
for stock_info in js_content['data']:
securityshortname = stock_info['securityshortname']
# print(securityshortname)
except Exception as e:
print(e)

async with lock:
count=count+1

print(f'count:{count}')
if count == pages:
print('End of loop')
loop.stop()



async def main():
global pages
global count
count=0
async with aiohttp.ClientSession() as session:
async with session.get(home_url.format(1), headers=headers) as resp:

content = await resp.text()
js_data = parse_json(content)
pages = js_data['pages']
print(f'pages: {pages}')
for page in range(1,pages+1):
task = asyncio.ensure_future(fetch(session,page))

await asyncio.sleep(1)


asyncio.ensure_future(main())
loop.run_forever()

1. 如果不加入锁,每次运行的结果可能不一样。
2. 不能用多线程的threading 锁,得到的每次运行结果也有可能不一样
3. 用asyncio的锁要 加关键字 async
 

attrs() got an unexpected keyword argument 'eq'

李魔佛 发表了文章 • 0 个评论 • 102 次浏览 • 2020-11-12 22:42 • 来自相关话题

xda@xda-dt:~$ pip install attrs --upgrade
Collecting attrs
  Downloading https://files.pythonhosted.org ... y.whl (49kB)
    100% |████████████████████████████████| 51kB 79kB/s 
Installing collected packages: attrs
  Found existing installation: attrs 18.2.0
    Uninstalling attrs-18.2.0:
      Successfully uninstalled attrs-18.2.0
Successfully installed attrs-20.3.0 查看全部
xda@xda-dt:~$ pip install attrs --upgrade
Collecting attrs
  Downloading https://files.pythonhosted.org ... y.whl (49kB)
    100% |████████████████████████████████| 51kB 79kB/s 
Installing collected packages: attrs
  Found existing installation: attrs 18.2.0
    Uninstalling attrs-18.2.0:
      Successfully uninstalled attrs-18.2.0
Successfully installed attrs-20.3.0

pyecharts绘图保存为图片 适用于ssh无头浏览器运行

李魔佛 发表了文章 • 0 个评论 • 119 次浏览 • 2020-11-04 22:27 • 来自相关话题

网上搜索到的答案是使用chrome driver实现的, 但是本人的程序是运行在centos下的,centos下折腾chrome driver比较蛋疼,所以看了下pyecharts.render的源码,其实这个也支持使用无头phantomjs进行截图的,当然这个不是一般的直接截取屏幕,是通过JS代码把html里面的渲染图像下载下来,清晰度比普通截图要高很多很多。
 

make_snapshot(snapshot, bar.render(), f"data/{today}_cb.png", driver=driver)
 
在最后一行传入一个driver既可以了,这个driver使用phantomjs的实例。
 
import os
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar
import sys
from selenium import webdriver
from pyecharts.commons.utils import JsCode

if sys.platform == 'win32':
SELENIUM_PATH = r'C:\OneDrive\Tool\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe'
driver = None
else:
SELENIUM_PATH = './phantomjs'
driver = webdriver.PhantomJS(executable_path=SELENIUM_PATH)


bar = (
Bar()
.add_xaxis(list(result_dict .keys()))
.add_yaxis(f"{today}-可转债价格分布", y_list, category_gap=3)
.add_yaxis(f"{today}-正股价格分布", y_zg_list, category_gap=3)
.set_series_opts(
label_opts=opts.LabelOpts(is_show=True),
axispointer_opts=opts.AxisPointerOpts(is_show=True))
.set_global_opts(
title_opts=opts.TitleOpts(title="可转债价格分布"),
xaxis_opts=opts.AxisOpts(
name="涨跌幅",
is_show=True,
name_rotate=30,
),
graphic_opts=[
opts.GraphicGroup(
graphic_item=opts.GraphicItem(
left="70%",
top="20%",
),
children=[
opts.GraphicText(
graphic_item=opts.GraphicItem(
left="center",
top="middle",
z=100,
),
graphic_textstyle_opts=opts.GraphicTextStyleOpts(
text=JsCode(
f"['涨幅>=0:{bigger}',"
f"'涨幅<0:{smaller}',"
f"'平均涨幅:{avg}%',"
f"'波动方差:{std}',"
f"'',"
f"'最大:{max_name} {max_pct}%',"
f"'最小:{min_name} {min_pct}%',"
"''].join('\\n')"
),
font="14px Microsoft YaHei",
graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
fill="#333"
)
)
)
]
)
],
)

)

bar.render(os.path.join('data', f"{today}_cb.html"))
make_snapshot(snapshot, bar.render(), f"data/{today}_cb.png", driver=driver)



  查看全部
网上搜索到的答案是使用chrome driver实现的, 但是本人的程序是运行在centos下的,centos下折腾chrome driver比较蛋疼,所以看了下pyecharts.render的源码,其实这个也支持使用无头phantomjs进行截图的,当然这个不是一般的直接截取屏幕,是通过JS代码把html里面的渲染图像下载下来,清晰度比普通截图要高很多很多。
 

make_snapshot(snapshot, bar.render(), f"data/{today}_cb.png", driver=driver)
 
在最后一行传入一个driver既可以了,这个driver使用phantomjs的实例。
 
import os
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar
import sys
from selenium import webdriver
from pyecharts.commons.utils import JsCode

if sys.platform == 'win32':
SELENIUM_PATH = r'C:\OneDrive\Tool\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe'
driver = None
else:
SELENIUM_PATH = './phantomjs'
driver = webdriver.PhantomJS(executable_path=SELENIUM_PATH)


bar = (
Bar()
.add_xaxis(list(result_dict .keys()))
.add_yaxis(f"{today}-可转债价格分布", y_list, category_gap=3)
.add_yaxis(f"{today}-正股价格分布", y_zg_list, category_gap=3)
.set_series_opts(
label_opts=opts.LabelOpts(is_show=True),
axispointer_opts=opts.AxisPointerOpts(is_show=True))
.set_global_opts(
title_opts=opts.TitleOpts(title="可转债价格分布"),
xaxis_opts=opts.AxisOpts(
name="涨跌幅",
is_show=True,
name_rotate=30,
),
graphic_opts=[
opts.GraphicGroup(
graphic_item=opts.GraphicItem(
left="70%",
top="20%",
),
children=[
opts.GraphicText(
graphic_item=opts.GraphicItem(
left="center",
top="middle",
z=100,
),
graphic_textstyle_opts=opts.GraphicTextStyleOpts(
text=JsCode(
f"['涨幅>=0:{bigger}',"
f"'涨幅<0:{smaller}',"
f"'平均涨幅:{avg}%',"
f"'波动方差:{std}',"
f"'',"
f"'最大:{max_name} {max_pct}%',"
f"'最小:{min_name} {min_pct}%',"
"''].join('\\n')"
),
font="14px Microsoft YaHei",
graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
fill="#333"
)
)
)
]
)
],
)

)

bar.render(os.path.join('data', f"{today}_cb.html"))
make_snapshot(snapshot, bar.render(), f"data/{today}_cb.png", driver=driver)



 

使用sshtunnel SSHTunnelForwarder 作为跳板连接mysql后一直卡住不退出

李魔佛 发表了文章 • 0 个评论 • 169 次浏览 • 2020-11-04 10:10 • 来自相关话题

代码如下:server = SSHTunnelForwarder(
ssh_address_or_host=host,
ssh_port=port,
ssh_username=user,
ssh_password=password,
local_bind_address=('127.0.0.1', local_port),
remote_bind_address=(host, mysql_port)
)

server.start()
conn = pymysql.connect(
host='127.0.0.1',
port=local_port,
user=user,
password=password,
db='db_stock'
)

cursor = conn.cursor()
cursor.execute('select count(*) from tb_cb_index')
ret = cursor.fetchall()
print(ret)
server.stop()
print('stop')

代码运行后并没有结束,或者没有答应stop的字符。 在程序里已经使用了server.stop()关闭ssh的连接。
 
后面发现日志里面,mysql的连接没有断开,导致server没有被关闭,所以在上面的代码中加一句:
 print(ret)
conn.close()
server.stop()
print('stop')
把mysql的连接关闭,然后就可以把ssh的连接关闭,然后打印stop字符了。
  查看全部
代码如下:
server = SSHTunnelForwarder(
ssh_address_or_host=host,
ssh_port=port,
ssh_username=user,
ssh_password=password,
local_bind_address=('127.0.0.1', local_port),
remote_bind_address=(host, mysql_port)
)

server.start()
conn = pymysql.connect(
host='127.0.0.1',
port=local_port,
user=user,
password=password,
db='db_stock'
)

cursor = conn.cursor()
cursor.execute('select count(*) from tb_cb_index')
ret = cursor.fetchall()
print(ret)
server.stop()
print('stop')

代码运行后并没有结束,或者没有答应stop的字符。 在程序里已经使用了server.stop()关闭ssh的连接。
 
后面发现日志里面,mysql的连接没有断开,导致server没有被关闭,所以在上面的代码中加一句:
 
print(ret)
conn.close()
server.stop()
print('stop')

把mysql的连接关闭,然后就可以把ssh的连接关闭,然后打印stop字符了。
 

pyecharts感觉这个库的设计有点业余,太过于反python了

李魔佛 发表了文章 • 0 个评论 • 110 次浏览 • 2020-11-03 01:09 • 来自相关话题

难道不知道python的数据分析用的是numpy的数据类型么?
 
一些扩展的类型int64作为数据导入到绘图函数中,居然不兼容,而且也不报错。 
经过逐个参数的排查,才发现是数据类型的问题。 数据是直接在pandas里面抽取出来的,然后填充到绘图汇总,然后就显示一片空白,还一直以为是我哪个参数用错了。
 
也许是从前端设计者手里接过来的项目吧。按葫芦画瓢这样操作。
 
一个函数里面居然可以放置几十个,上百个参数,我滴神呀,而且参数里面还有其他类型的参数,尼玛!

 
当然最让人头疼是那往上不兼容的做法,现在的新版本完全已经修改了,不兼容旧版本,之前的写代码又是一通修改。 查看全部
难道不知道python的数据分析用的是numpy的数据类型么?
 
一些扩展的类型int64作为数据导入到绘图函数中,居然不兼容,而且也不报错。 
经过逐个参数的排查,才发现是数据类型的问题。 数据是直接在pandas里面抽取出来的,然后填充到绘图汇总,然后就显示一片空白,还一直以为是我哪个参数用错了。
 
也许是从前端设计者手里接过来的项目吧。按葫芦画瓢这样操作。
 
一个函数里面居然可以放置几十个,上百个参数,我滴神呀,而且参数里面还有其他类型的参数,尼玛!

 
当然最让人头疼是那往上不兼容的做法,现在的新版本完全已经修改了,不兼容旧版本,之前的写代码又是一通修改。

python打造3D撞球小游戏

wanbainip 发表了文章 • 0 个评论 • 146 次浏览 • 2020-10-26 15:52 • 来自相关话题

万变ip给大家分享一下制作炫酷动画所需的全部代码。








我们需要三组刚体(当您在Blender的对象上打开一个刚体的属性时,Blender将模拟与其它刚体的碰撞):

1.平面

第2行代码创建了一个简单的平面,立方体将放置在该平面上。为了防止它因重力而坠落,我们将其设为“受体”第4行代码。

2. 圆环














第11-12行将第一个圆环的"Enabled"属性设置为false,防止由于重力而坠落。这样它就固定在那牵住整个链条。

3. 立方体












因为z循环第13行嵌套在x循环[第5行]中,我们将得到一个18X10的立方体组成的墙。 查看全部
万变ip给大家分享一下制作炫酷动画所需的全部代码。

1.png




我们需要三组刚体(当您在Blender的对象上打开一个刚体的属性时,Blender将模拟与其它刚体的碰撞):

1.平面

第2行代码创建了一个简单的平面,立方体将放置在该平面上。为了防止它因重力而坠落,我们将其设为“受体”第4行代码。

2. 圆环



2.png








第11-12行将第一个圆环的"Enabled"属性设置为false,防止由于重力而坠落。这样它就固定在那牵住整个链条。

3. 立方体



3.png






因为z循环第13行嵌套在x循环[第5行]中,我们将得到一个18X10的立方体组成的墙。

pipreqs python3 不兼容问题解决

李魔佛 发表了文章 • 0 个评论 • 193 次浏览 • 2020-10-21 16:02 • 来自相关话题

这里面可能会报几个错误:
 
1. 如果报错信息是:
如果提示“UnicodeDecodeError: 'gbk' codec can't decode ”的错误,需要指定字符集 --encoding=utf8

pipreqs ./ --encoding=utf8
 
 2. 出现诸如:Traceback (most recent call last):
File "c:\anaconda\envs\py37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\anaconda\envs\py37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\anaconda\envs\py37\Scripts\pipreqs.exe\__main__.py", line 7, in <module>
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 470, in main
init(args)
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 409, in init
follow_links=follow_links)
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 138, in get_all_imports
raise exc
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 124, in get_all_imports
tree = ast.parse(contents)
File "c:\anaconda\envs\py37\lib\ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 162
except Exception ,e:
^
SyntaxError: invalid syntax
明显的python2的语法报错,这时很可能是你的项目中有python2语法的py文件,可以使用
--ignore <dirs> ...忽略额外的目录
 
参数解决。
 
 原文链接:
http://30daydo.com/article/619
转载请注明出处 查看全部
这里面可能会报几个错误:
 
1. 如果报错信息是:
如果提示“UnicodeDecodeError: 'gbk' codec can't decode ”的错误,需要指定字符集 --encoding=utf8

pipreqs ./ --encoding=utf8
 
 2. 出现诸如:
Traceback (most recent call last):
File "c:\anaconda\envs\py37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\anaconda\envs\py37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\anaconda\envs\py37\Scripts\pipreqs.exe\__main__.py", line 7, in <module>
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 470, in main
init(args)
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 409, in init
follow_links=follow_links)
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 138, in get_all_imports
raise exc
File "c:\anaconda\envs\py37\lib\site-packages\pipreqs\pipreqs.py", line 124, in get_all_imports
tree = ast.parse(contents)
File "c:\anaconda\envs\py37\lib\ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 162
except Exception ,e:
^
SyntaxError: invalid syntax

明显的python2的语法报错,这时很可能是你的项目中有python2语法的py文件,可以使用
--ignore <dirs> ...忽略额外的目录
 
参数解决。
 
 原文链接:
http://30daydo.com/article/619
转载请注明出处

pycharm实用插件

李魔佛 发表了文章 • 0 个评论 • 153 次浏览 • 2020-10-17 02:25 • 来自相关话题

1. rainbow bracket
括号对变成彩色的
2. kite
人工智能预测输入提示: 根据机器学习,预测你下一个输入函数的名
 
1. rainbow bracket
括号对变成彩色的
2. kite
人工智能预测输入提示: 根据机器学习,预测你下一个输入函数的名
 

asyncio中get_running_loop和get_event_loop的区别

李魔佛 发表了文章 • 0 个评论 • 387 次浏览 • 2020-10-10 17:03 • 来自相关话题

asyncio.get_running_loop()

asyncio.get_event_loop()
 
官方地址
https://docs.python.org/3/library/asyncio-eventloop.html?highlight=get_running_loop#asyncio.get_running_loop
 
get_running_loop() 是python3.7之后新增的函数,用于获取当前正在运行的loop,如果当前主线程中没有正在运行的loop,如果没有就会报RuntimeError 错误。
 
并且get_running_loop 要在协程里面用,用来捕获当前的loop。
 
示例用法: 1 # -*- coding: utf-8 -*-
2
3 import asyncio
4
5 async def main():
6 await asyncio.sleep(10)
7 print('Done')
8 myloop = asyncio.get_running_loop()
9 print('current loop ')
10 print(id(myloop))
11
12 # loop = asyncio.get_running_loop()
13 loop = asyncio.get_event_loop()
14 print('current loop id')
15 print(id(loop))
16
17 # print(id(myloop))
18 try:
19 loop.run_until_complete(main())
20 except KeyboardInterrupt:
21 print('key board inpterrupt!')



运行结果:





可以看到两个loop的id是一样的,是同一个对象。
如果第十二行直接调用的话会报错。
asyncio.get_event_loop() 如果在主线程中,如果没有被设置过任何event loop (时间循环),那么会创建一个时间循环,并返回。
  查看全部
asyncio.get_running_loop()

asyncio.get_event_loop()
 
官方地址
https://docs.python.org/3/library/asyncio-eventloop.html?highlight=get_running_loop#asyncio.get_running_loop
 
get_running_loop() 是python3.7之后新增的函数,用于获取当前正在运行的loop,如果当前主线程中没有正在运行的loop,如果没有就会报RuntimeError 错误。
 
并且get_running_loop 要在协程里面用,用来捕获当前的loop。
 
示例用法:
  1 # -*- coding: utf-8 -*-
2
3 import asyncio
4
5 async def main():
6 await asyncio.sleep(10)
7 print('Done')
8 myloop = asyncio.get_running_loop()
9 print('current loop ')
10 print(id(myloop))
11
12 # loop = asyncio.get_running_loop()
13 loop = asyncio.get_event_loop()
14 print('current loop id')
15 print(id(loop))
16
17 # print(id(myloop))
18 try:
19 loop.run_until_complete(main())
20 except KeyboardInterrupt:
21 print('key board inpterrupt!')



运行结果:

Screenshot_from_2020-10-10_17-03-55.png

可以看到两个loop的id是一样的,是同一个对象。
如果第十二行直接调用的话会报错。
asyncio.get_event_loop() 如果在主线程中,如果没有被设置过任何event loop (时间循环),那么会创建一个时间循环,并返回。
 

python3.8海象运算符

李魔佛 发表了文章 • 0 个评论 • 276 次浏览 • 2020-09-08 23:13 • 来自相关话题

海象运算符( := )

这个「:=」横过来看是不是有点像海象的脸?这是一个新的 Python 语法,可以在进行条件判断时直接为变量赋值。

过去我们需要首先对某个变量进行赋值,然后进行条件判断。m = re.match(p1, line)
if m:
return m.group(1)
else:
m = re.match(p2, line)
if m:
return m.group(2)
else:
m = re.match(p3, line)
...
 而使用海象运算符后,我们可以直接为变量赋值:
if m := re.match(p1, line):
return m.group(1)
elif m := re.match(p2, line):
return m.group(2)
elif m := re.match(p3, line):
PS:
python的版本更新最喜欢搞这一类的小动作,仅仅为了节省那么一两行代码弄得代码无法向下兼容。

  查看全部
海象运算符( := )

这个「:=」横过来看是不是有点像海象的脸?这是一个新的 Python 语法,可以在进行条件判断时直接为变量赋值。

过去我们需要首先对某个变量进行赋值,然后进行条件判断。
m = re.match(p1, line)
if m:
return m.group(1)
else:
m = re.match(p2, line)
if m:
return m.group(2)
else:
m = re.match(p3, line)
...

 而使用海象运算符后,我们可以直接为变量赋值:
if m := re.match(p1, line):
return m.group(1)
elif m := re.match(p2, line):
return m.group(2)
elif m := re.match(p3, line):

PS:
python的版本更新最喜欢搞这一类的小动作,仅仅为了节省那么一两行代码弄得代码无法向下兼容。