python 版本查看

jupyter中执行

 
import sys
!{sys.executable} --version
Python 3.9.17

python编码文件头

 
# -*- coding: UTF-8 -*-
或者
# coding=utf-8

python 测速

timeit

 
import timeit

code_to_test = """
for i in range(10000):
    pass
"""

elapsed_time = timeit.timeit(code_to_test, number=1)

print("代码执行1次的平均时间为:", round(elapsed_time*1000*1000), "微秒") 

输出: 
代码执行1次的平均时间为: 184 微秒

profile

 
import profile

def foo():
    for i in range(10000):
        pass

profile.run("foo()")

 
5 function calls in 0.000 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 2701821783.py:3(foo)
        1    0.000    0.000    0.000    0.000 :0(exec)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.000    0.000    0.000    0.000 string:1(module)
        1    0.000    0.000    0.000    0.000 profile:0(foo())
        0    0.000             0.000          profile:0(profiler) 

 

    

 
import time

# 记录开始时间
start_time = time.time()

# 你想要测量执行时间的代码块
# 例如,这里我们用一个简单的循环来模拟一些工作
for i in range(1000000):
    pass  # 这是一个空操作,只是为了模拟一些工作

# 记录结束时间
end_time = time.time()

# 计算执行时间
execution_time = end_time - start_time

print(f"执行时间: {execution_time:.6f} 秒")



    

 


 

  

 


python crontab

 
from tempfile import NamedTemporaryFile
import os

def add_crontab_on_reboot(file):
    with os.popen("crontab -l", "r") as pipe:
        current = pipe.read()
    current += f"@reboot /home/xt/anaconda3/bin/python {file}\n"
    with NamedTemporaryFile("w") as f:
        f.write(current)
        f.flush()
        os.system(f"crontab {f.name}")
        
def add_crontab(file):
    with os.popen("crontab -l", "r") as pipe:
        current = pipe.read()
    current += f"40 16 * * * /home/xt/anaconda3/bin/python {file}\n"
    with NamedTemporaryFile("w") as f:
        f.write(current)
        f.flush()
        os.system(f"crontab {f.name}")
        
def clear_crontab():
    with NamedTemporaryFile("w") as f:
        f.write("\n")
        f.flush()
        os.system(f"crontab {f.name}")
        
def get_crontab():
    with os.popen("crontab -l", "r") as pipe:
        current = pipe.read()
    print(current)
        

        
get_crontab()   
    
python 队列

collections.deque: 定长,进一个,自动出一个

 
import collections 

data_index = 0
def test_queue():
    global data_index
    span = 5
    buffer = collections.deque(maxlen=span)   # 队列

    for i in range(span):
        buffer.append(data_index)
        data_index = data_index +1

    print("query len:",len(buffer))
    for i in range(10):
        buffer.append(data_index)
        data_index = data_index +1
        print("first value:",buffer[0],", query len:",len(buffer))

test_queue()

query len: 5
first value: 1 , query len: 5
first value: 2 , query len: 5
first value: 3 , query len: 5
first value: 4 , query len: 5
first value: 5 , query len: 5
first value: 6 , query len: 5
first value: 7 , query len: 5
first value: 8 , query len: 5
first value: 9 , query len: 5
first value: 10 , query len: 5

python queue.Queue

 
import queue
# maxsize 队列的最大长度 
# 队列满后,程序被阻塞
# 若为零,则不限长度 
q = queue.Queue(maxsize=3)

q.put(1)
q.put(2)
q.put(3)

q.qsize()
3 

q.full()
True 

下面这段代码不会报错,而是被阻塞,一直等待...

 
try:
    q.put(4)
except queue.Full:
    print("queue full")

python eval

不包含字母的表达式

 
ss = "[1,2,3,4,5]"
print(type(eval(ss))) # list

包含字母的表达式

 
a=1
ss="a>2"
print(eval(ss))  # False

python格式化

元组format

 
a=('a','b')
ss="{}".format(a)  #"('a', 'b')" 
b=eval(ss)
type(b) # tuple

数字前补0


start_hour = 1
print("%02d"%start_hour) # 01

数字前面本没有0,补了0之后,就不再是数字了

 
num_count = 3
for i in range(num_count):
    res = '%019d'%i
    print(res,type(res))

输出:
0000000000000000000 class 'str'
0000000000000000001 class 'str'
0000000000000000002 class 'str'

python global

global:让一个局部变量升级为全局变量,哪所你写层嵌套,哪怕写到方法里

 
aa = 1

class A:
    def a(self):
        global aa 
        aa = 2
        
class B:
    def b(self):
        global aa 
        aa = 2*aa      
        
ca = A()
cb = B()
ca.a()
cb.b()
cb.b()

aa最后为8

python 空值处理

列表的空

 
ll = []
if ll:
    print('有')
else:
    print('空')

输出: 
空 

该用法较少,更多的写法是取列表长度,直接判断长度是否为0 

字符串首尾的空

 
去除首尾的空格
ll = " a b c ".strip()
ll
'a b c'

zip配对取值

数组

 
a=["aa","bb"]
b=[11,22]
for i,(j,k) in enumerate(zip(a,b)):
    print(i,j,k)

输出:
0 aa 11
1 bb 22

字符串

 
a="abb"
b="123"
for i,(j,k) in enumerate(zip(a,b)):
    print(i,j,k)

输出:
0 a 1
1 b 2
2 b 3

a="ab b"
b="12 3"
for i,(j,k) in enumerate(zip(a,b)):
    print(i,j,k)

输出:
0 a 1
1 b 2
2    
3 b 3

python 取整

 
import math
rownum = 6
interval = 3
math.ceil(rownum / interval)
2

rownum = 7
interval = 3
math.ceil(rownum / interval)
3

python 退出程序

 
import sys
sys.exit(0)

python 异常处理

try except Exception as e

 
try:
    _mysql = pymysql.connect(host=db_dict["db1.host"],
                port=db_dict["db1.port"],
                user=db_dict["db1.username"],
                password=db_dict["db1.password"],
                database=db_dict["db1.database"],
                charset=db_dict["db1.charset"])

except  Exception as e:
    error_msg = "{} {} {} {}  mysql db connect error".format(db_dict["db1.host"],db_dict["db1.port"],
                                                     db_dict["db1.username"],
                                 
                                                     db_dict["db1.database"])
    print(error_msg)
    print(e)

通常情况下,要打印出原来的异常信息,在异常触发时可以更好地定地问题
同时,也自己写一个辅助的信息,对异常进行补充

python整数范围

[-9223372036854775808,9223372036854775807]

 
a=9223372036854775807
a-1
9223372036854775806

92万亿
19位数,且开头第1位是9,很大的一个数,这个数用来做库表的ID,通常够用 

a=-9223372036854775808
a+1
-9223372036854775807

参考