python基础 必备知识

发布于:2023-01-04 ⋅ 阅读:(401) ⋅ 点赞:(0)

python跑的demo

放在vscode里面跑,只要是能跑起来

#!/usr/bin/python3
# -*- coding: utf-8 -*-

print("Hello,world!")

在这里插入图片描述
类对象self
参考文章:python 类,实例,方法
写一个demo:openpyxl读取excel某一行的内容

# 类 变量初始化
class Caculate:
    def __init__(self,x,y):
        self.x = x
        self.y = y

caculate = Caculate(1,100)
print(caculate.x)
print(caculate.y)
# 类 成员变量初始化 方法 ,类中定义多个函数相互调用
class Caculate:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def sum(self):
        c = self.x + self.y
        return c
    
    def reduct(self):
        c = self.x - self.y
        return c

    def res(self):
        c = self.sum() + self.reduct()
        return c

caculate = Caculate(100,10)
print(caculate.sum())
print(caculate.reduct())
print(caculate.res())
# 传参时初始化
class Caculate:
    def __init__(self,y):
        self.y = y
        self.x = 0

    def sum(self):
        c = self.x + self.y
        return c
    
    def reduct(self,x):
        self.x = x
        c = self.x - self.y
        return c


caculate = Caculate(100)
caculate.x = 105
print(caculate.sum())
print(caculate.reduct(caculate.x))

python常用

变量 类型

全局变量

#前后端
BACKEND=2
FRONDEND=3

数值操作

# 获取绝对值
print(abs(num))
# 浮点型 保留小数
# 示例:trace-test-log 变化率:115.44 变化量:76600 当前大小:942800
方法1:data = "索引:%s 变化率:%.2f% 变化量:%d 当前大小:%d\n" % (indice_name,indice_diff_precent,indice_diff_size,indice_later_size)
方法2:round(pro_msg/pro_num, 4)

参考文章:python求绝对值的三个方法
参考文章:python 保留浮点数为两位小数
类型转换

# 数字转字符串
b=str(a)
# 字符串转数字
int(d)

参考文章:Python中如何将数值转换为字符串?

判断变量类型

if isinstance(propath,str):
    print("是字符串")
# 判断变量是否为空
if text is None:
	print("是空")

参考文章:Python中判断Nonetype的方法
参考文章:判断变量是否为空

数组 元组 遍历

数组 遍历

# 遍历数组
for item in sequence:
    print item
# 遍历数组 需要取到索引
for index in range(len(sequence)):
       print index,sequence[index]
# 数组遍历 追加
mysql_setting_list = ['--socket=/tmp/mysql-30081.sock', '--port=30081',
            '--socket=/tmp/mysql-30082.sock', '--port=30082']
ports_list = [i for i in mysql_setting_list if i.find("--port") != -1]
print(ports_list)   #['--port=30081', '--port=30082']
ports_list = [i.split("=")[1] for i in mysql_setting_list if i.find("--port") != -1]
print(ports_list)   #['30081', '30082']

数组追加 去重

  • 数组追加
a = ['a','b','c']
a.append('d')

参考文章:【Python基础】将一个list完整的添加到另一个list中(不同于逐个元素添加在尾部)

参考文章:python学习笔记之两个list之间的差异(差集、交集、并集、查重)

list_a = ['1', '2', '3', '4']
list_b = ['1', '2', '3', '5','6','7']
 
# list_a对应list_b的差集
diff_a_b = set(list_a).difference(set(list_b))
print('list_a对应list_b的差集:', diff_a_b) #示例:list_a对应list_b的差集: {'4'}

# list_a对应list_b的差集
# 示例:未备份区组list-->[u'20008']  备份为空区组list-->['5025']
empty_dist_list = [x for x in empty_list if x in dist_info]

获取元组
参考文章:Python 元组
在这里插入图片描述
数组 元组 转换
参考文章:python 列表、元组、字符串 相互转换
参考文章:python中如何实现元组与列表相互转换

t1 = ('a','b','c','d','e')
l1 = list(t1)

字典 遍历

字典 初始化 赋值 遍历

# 字典初始化
spam=dict()
spam["A"]=1
spam["B"]="错误"    
# 字典初始化,通过key获取value
spam = {"A":123 ,"B":345,"C":345 }
print(spam["A"])
spami = spam.get("A", "0") #字典获取默认值
# 字典 key value遍历
all_count = {}
ports = ['9020','9030','9040']
for port in ports:
    all_count[port] = "True"
print(all_count)  #{'9020': 'True', '9030': 'True', '9040': 'True'}
for key in all_count:
    print(key,'---',all_count[key])  #通过key获取value 示例:9020 --- True
# 字典 key value遍历
nginx_busibess = {"wjpt_outnginx_prod_conf" : "154.8.188.193",
                  "wjpt_innernginx_prod_conf" : "10.12.51.10"}
for nginx_file,vip in nginx_busibess.items() :
    print(nginx_file,'---',vip)
# 字典按照value排序
pro_msg_sort = sorted(pro_dict.items(), key=lambda item: item[1], reverse=True)  # 按value进行降序

字典数组 遍历 查找
参考文章:Python:根据键的值在数组中查找字典

dist_ccs_info = [{'main_name': '问道', 'sub_name': '国士无双', 'ass_ip': '10.26.107.13', 'ass_gysn': 'TM3163'},
                {'main_name': '问道', 'sub_name': '霞举飞升', 'ass_ip': '10.26.107.10', 'ass_gysn': 'TM3143'}]
dist_name = '国士无双'
dist_ccs_msg = [dist_ccs_i for dist_ccs_i in dist_ccs_info if dist_ccs_i["sub_name"] == dist_name]
print(dist_ccs_msg) # 示例:[{'main_name': '问道', 'sub_name': '国士无双', 'ass_ip': '10.26.107.13', 'ass_gysn': 'TM3163'}]

函数 命令行 传参 获取

获取命令行输入

import sys

def getxlsx:
    if len(sys.argv)!=2:
        sys.exit()
    else:
        print(sys.argv[1]) #输出命令行输入的第一个参数
python test.py '{"parrot": 42, "spam": "foo"}'

参考文章:python获得命令行输入的参数的两种方式
参考文章:python怎么退出程序

  • 退出python命令行:ctrl+z

参考文章:如何退出python命令行
函数 传参 获取返回值

def test(num):
    result=num+2
    return result

num=test(1)
print(num)

函数 传参 获取多个返回值
我想返回多个参数–>用字典返回
字典初始化,调用函数接收字典,通过key获取value
参考文章:Python函数中如何返回多个值?

def aa():
    spam=dict()
    spam["A"]=1
    spam["B"]="错误"    
    return spam

res=aa()
print(res["A"])

函数修改全局变量
参考文章:python函数里引用全局变量

BACKEND=2
FRONDEND=3
global PRONAME_COL    #proname

def aa():
    global PRONAME_COL
    PRONAME_COL = 2

aa()
print(PRONAME_COL)

判断 异常

判断
且 and 或 or

if 条件表达式 :
    代码块
elif 条件表达式 :
   代码块 
else :
   代码块 

参考文章:python判断语句
判断 捕获异常
不希望程序有error,就异常退出
try无异常执行else,有异常则执行expect

for appmsg in cur:
    app_id=appmsg[0]
    try:
        upadtemsg="update job_app set src_game_id=5 where app_id="+app_id
        cur.execute(upadtemsg)
    except Exception as e:
        print("更新失败", e)
	else:
		.....

执行shell 并发

执行shell

# 导入模块
from subprocess import call
import os
# 基本需求:执行shell
import os
cmd = "mkdir ./temp"    
call(cmd, shell=True) 

# 进一步需求:执行shell,希望可以带上变量
filepkg=/root/doc/6666.tar.gz
cmd="tar -xzf "+filepkg+" -C ./temp"
call(cmd,shell=True)
# 进一步需求:执行shell,字符串拼接 
cmd="grep -rn tag "+path+" | grep '\.txt' | awk '{print$NF}'" #.有特殊含义,用转义符去特效

# 进一步需求:获取shell执行结果
# 方法1:除去空白符 这里主要想除去换行符
psinfo = os.popen("ps auxww | grep mysqld | grep -v grep").read().strip()
# 方法2:除去空白符 这里主要想除去换行符
import subprocess
child = subprocess.Popen("echo ~", shell=True, stdout=subprocess.PIPE)
homedir = child.stdout.read().strip()
print(homedir)
# 将结果转为数组
psinfo = os.popen("ps auxww | grep mysqld | grep -v grep").read().split()
# 将结果转为数组 遍历结果
cmd="ps -ef | grep mysql"
child=os.popen(cmd)
for i in child.readlines():
    print(i)

参考文章:Python调用shell命令常用方法,os的一些使用方法
参考文章:Python之系统shell交互(subprocess)
win10 有linux环境
Win 10安装cywin 有linux环境
https://cygwin.com/
.exe文件地址:https://cygwin.com/setup-x86_64.exe
参考文章:Windows10安装Cygwin教程
在这里插入图片描述
并发 提高效率
参考文章:怎么提高python 中for循环的的效率

  • 数组实例并发执行
#!/usr/bin/env python
#_*_coding:utf-8_*_

# python 2.7.13
from multiprocessing import Pool, Manager
import sys
reload(sys)
sys.setdefaultencoding('utf8')  

# 用于多进程间共享资源,普通list无法共享
result_list = Manager().list() 

def smartping_check(ass_ip,dist_id):
    '''
    smartping 检查结果
    通过smartping /api/alert.json 接口获取报警数据
    :param ass_ip,dist_id
    :return:
    '''
    dist_info = ('run ass_ip:{} dist_id:{}'.format(ass_ip,dist_id))
    print(dist_info) #示例:run ass_ip:10.14.109.27 dist_id:6003
    result_list.append(dist_info)

# 数组示例异步执行
ucenter_result = []  # len(ucenter_result)=51
pool = Pool(4)
pool_list = []
for i in ucenter_result:
    # 示例:sub_name:泰来虎ass_ip:10.14.109.86 dist_id:6004
    print('sub_name:{}ass_ip:{} dist_id:{}'.format(i['sub_name'],i['ass_ip'],i['dist_id']))
    pool_list.append(pool.apply_async(smartping_check,args=(i['ass_ip'],i['dist_id'],)))
pool.close()
pool.join()
print(result_list)

在这里插入图片描述

from concurrent.futures import ThreadPoolExecutor

# python3
def smartping_check(ass_ip,dist_id):
    '''
    smartping 检查结果
    通过smartping /api/alert.json 接口获取报警数据
    :param ass_ip,dist_id
    :return:
    '''
    dist_info = ('run ass_ip:{} dist_id:{}'.format(ass_ip,dist_id))
    print(dist_info) #示例:run ass_ip:10.14.109.27 dist_id:6003
 
# 数组示例异步执行
get_ucenter_info = [] # len(get_ucenter_info) = 51
thread_pool = ThreadPoolExecutor(max_workers=4)
 
for i in ucenter_result:
    # 示例:sub_name:泰来虎ass_ip:10.14.109.86 dist_id:6004
    print('sub_name:{}ass_ip:{} dist_id:{}'.format(i['sub_name'],i['ass_ip'],i['dist_id']))
    thread_pool.submit(smartping_check,i['ass_ip'],i['dist_id'])
thread_pool.shutdown()

在这里插入图片描述

编码 时间

编码
参考文章:UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 41-50: ordinal not in range(

#!/usr/bin/python
# coding=utf-8

aaa= "小卡骄傲"
print(aaa)  #小卡骄傲
print(aaa.encode('utf-8')) #b'\xe5\xb0\x8f\xe5\x8d\xa1\xe9\xaa\x84\xe5\x82\xb2'
print(aaa.encode('utf-8').decode('latin-1')) #å°å¡éª

报错:SyntaxError: Non-ASCII character ‘\xe5’ in file 编码错误
参考文章:SyntaxError: Non-ASCII character ‘\xe5’ in file 的解决办法
在你程序开始的地方加入(程序最最顶端)以下代码即可:

#!usr/bin/python
# -*- coding: utf-8 -*-
  • python2 乱码

参考文章:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)

import sys
reload(sys)
sys.setdefaultencoding('utf8')  

时间
模块导入

import datetime
import time

获取当前时间
参考文章:python获取当前时间的用法

import datetime
now_time = datetime.datetime.now()
now_time_str = datetime.datetime.strftime(now_time,'%Y-%m-%d %H:%M:%S')
print(now_time_str)

i = datetime.datetime.now()
ntime = '%s-%s-%s %s:%s:00'%(i.year,i.month,i.day,i.hour,i.minute) #时间示例2022-8-5 9:27:00

通过时间戳获取时间
时间戳生成参考文章:Python获取秒级时间戳与毫秒级时间戳的方法
参考文章:Python中timestamp和日期时间的转换

# 方法1
ts = 1568172006.68132 # 时间戳
format = '%Y-%m-%d %H:%M:%S' # 根据此格式来时间戳解析为时间字符串
# 时间戳转time.struct_time
ts_struct = time.localtime(ts)
# time.struct_time转时间字符串
date_string = time.strftime(format, ts_struct)

print(date_string) # '2019-09-11 11:20:06'

# 方法2
dt = datetime.datetime.fromtimestamp(ts)
date_string = dt.strftime(format)
print(date_string)

时间间隔 时间偏移
参考文章:python简单获取两个日期之间的年度、月度、天数差的方法

# 计算时间间隔,天、月
from datetime import datetime
import datetime

def days(str1,str2):
    date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
    date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
    num=(date1-date2).days
    return num
def months(str1,str2):
    year1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d").year
    year2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d").year
    month1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d").month
    month2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d").month
    num=(year1-year2)*12+(month1-month2)
    return num

now_time = datetime.datetime.now()
now_time_str = datetime.datetime.strftime(now_time,'%Y-%m-%d %H:%M:%S')
print(now_time_str)
res=months(now_time_str,'2021-01-23')
print(res)

日期时间偏移,加减
参考文章:Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年一月,时区转换

from datetime import datetime
import datetime

moni_start='2022-01-18 12:00:00'
moni_startafter=str(datetime.datetime.strptime(moni_start,'%Y-%m-%d %H:%M:%S')+datetime.timedelta(days=1))

python安装与问题解决

python安装

python安装
win安装pythin 参考文章:可能是全网最详细的 Python 安装教程(windows)
安装python2
在这里插入图片描述
linux安装python
参考文章:Linux(Ubuntu)系统安装Python
Centos7 下安装python3及卸载
参考文章:Centos7 下安装python3及卸载
grep -l “abc” ./* |xargs rm -rf
删除当前目录下包含“abc”的文件
安装时可能出现:ModuleNotFoundError: No module named ‘_ctypes’
1、执行如下命令:
yum install libffi-devel
2、从"./configure …"重新安装
参考文章:Python安装报错:”ModuleNotFoundError:No module named _ctypes“ 的解决方案

Win10安装Ansible Python包

在win环境下直接使用pip install ansible安装肯定是会报错的,原因大概是,在安装ansible时,有一个测试套件中符号链接的过程,因为符号链接路径太长,win10无法创建这个目录树,最后因为找不到对应的符号链接,安装就失败了。
在这里插入图片描述
参考文章:Win10安装Ansible Python包

pip 安装模块

pip 升级
Pip历史版本:https://pypi.org/project/pip/21.1.2/
参考文章:更新pip源

python -m ensurepip
python -m pip install --upgrade pip

pip 模块指定版本
参考文章:pip install指定版本

pip3 install django==2.1.4

安装模块 timeout 超时
参考文章:pip安装openpyxl失败,更换镜像源
在这里插入图片描述
不是timeout了吗,请求超时,那就更改源
百度搜索关键词:openpyxl pip 源

pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/

报错“拉取失败 could not fetch URL https://pypi.org/simple/pip/
说明源有问题
在这里插入图片描述
模块离线安装参考:Python——安装requests第三方库
pip install django -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
参考文章:pip安装一个第三方的库,就一直报错
报错:导入模块 “ModuleNotFoundError: No module named ‘pip’” ubuntu

sudo apt install --fix-missing python3-pip

参考文章:“ModuleNotFoundError: No module named ‘pip’”的解决方法都在这!(ubuntu)
报错:RequestsDependencyWarning: urllib3 (1.25.2) or chardet (3.0.4) doesn’t match a supported version!
参考文章:RequestsDependencyWarning: urllib3 (1.25.2) or chardet (3.0.4) doesn’t match a supported version!
报错:Script file ‘D:\software_install\Anaconda_install\Scripts\pip-script.py‘ is not present pip损毁
参考文章:错误:Script file ‘D:\software_install\Anaconda_install\Scripts\pip-script.py‘ is not present.完美解决方法

模块导入失败

报错:import “package“ could not be resolved
pip list中又有,这咋回事
参考文章:VSCode警告 Import “package“ could not be resolved
在这里插入图片描述
问题:可能是因为循环依赖
参考文章:人工智能 ImportError: cannot import name app解决办法,循环依赖解决

pyc反编译

参考文章:python代码加密——编译与反编译方法总结
pyc反编译传送门:https://tool.lu/pyc/
在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到