python常用接口调用

字符串

  1. 字符串中查找匹配
str.find(str1) 
a='dog'
>>> a.find('go')   不存在,局部也不行,返回-1
-1
>>> a.find('og') 存在,但不是从头开始一致,返回1
1
>>> a.find('do') 存在,包含和完全一致,返回0
0

直接对比 if a in b

  1. 判断字符串内容, 比如是纯数字or纯字母
str.isalnum() 所有字符都是数字或者字母
str.isalpha() 所有字符都是字母
str.isdigit() 所有字符都是数字
str.islower() 所有字符都是小写
str.isupper() 所有字符都是大写

回到目录

  1. 字符串大小写转换
str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 


WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

split和strip的区别
split和strip的区别

大小写编码/字符判断

查看字符编码ord(str)

ord('a')=97    查看字符编码id
小写字符ord编码 : 97-122
大写字符ord编码 :    65-90
if str in range(97,123)  判断单个字符是小写

字典

字典形式
d = {key1 : value1, key2 : value2 }
  • 创建字典 dic={}

  • 赋值操作dic[key]=value
    重复赋相同的值,只出现一次

  • 查找操作 If key in dic
    返回value, 查value是找不到的

  • 按元素放入的先后顺序进行排序

         import collections
         dict = collections.OrderedDict()
from collections import defaultdict

d = defaultdict(list)  # list只是属性声明,并不需要替换成真正定过后的list
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)

多个值去重后再映射

d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
  • 字典按照value值排序
sorted_dict = dict(sorted(dur_dict.items(), key=lambda item: item[1]))

集合

集合形式
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
  • 创建集合 a = set()
  • 添加元素 a.add('x') 如果已经有的是添加不上的
  • 移除某个元素 a.remove('x')
  • 查找 `if ‘x’ in a

列表

  1. 可以当作栈结构使用
list.append(x)  默认加在列表的最后一位
list.pop()  默认弹出的最后一位
list.remove(target) 移除特定的元素
list.reverse() 对列表进行翻转
list.index(obj)  找到对象obj的索引index
list.insert(index, obj) 在对应索引的位置插入对象
list.count(obj)  计算对象obj在index中出现的次数
list.extend(seq) 一次性在列表后添加多个数值, 也可以用  list1+list2  的形式

注意,弹出的时候要判断list是否为空,否则在严格的判断中是会报错的

a=list.pop() if list else '#'
  1. list拼接a+b

  2. 列表和集合相互切换

mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto))        #列表去重
print(addr_to)
addr_to.sort(key=mailto.index)    # 按照列表原顺序进行恢复
print(addr_to)
  1. 判断元素在a中不在列表b中
subtract_list = list(set(a).difference(set(b)))
  1. list中元素挑选
tar_wav_list = list(filter(lambda x: x.startswith(start_str), wav_list)) ----将wav_list中元素1⃣️‘a'开头的挑选出来组成新的tar_wav_list

数组numpy

  1. 1维数组反转a=array([0,1,2]), a[::-1]------[2,1,0]
  2. 将数组排序
array([[1, 2, 4, 6],
       [1, 4, 5, 8]])
>>> a=np.array([[4,1,6,2],[5,1,4,8]])
>>> a
array([[4, 1, 6, 2],
       [5, 1, 4, 8]])
>>> np.sort(a)
array([[1, 2, 4, 6],
       [1, 4, 5, 8]])        # 直接展示数组从小到大排序后的结果,默认按行排序
>>> np.sort(a, axis=0)
array([[4, 1, 4, 2],
       [5, 1, 6, 8]])       # 指定维度排序
>>> np.argsort(a)
array([[1, 3, 0, 2],
       [1, 2, 0, 3]])            ## 将数组a按照从小到大的结果展示index,然后可以选择最大的几维

  1. 数据四舍五入
>>> int(1.799999)
1
>>> round(1.799999)
2
  1. 数组中数据选择(条件)
condition = data_array>1
f0_array = np.extract(condition, data_array) --------将数组中数值大于1的挑选出来,组成新的f0_array
  • 读入大文件,mmap的方式,让大文件一部分先放在硬盘上,不是完全读取
np.load(input_file, mmap_mode = 'r')

标准输入模板

  • 样例1–数字类型
    输入第一行包括一个数据组数t(1 <= t <= 100)
    接下来每行包括两个正整数a,b(1 <= a, b <= 10^9) ,输出a+b
    e.g.输入
#输入
2
1    5
10   20
输出
6
30
import sys
lines = list(sys.stdin)
#对第一行单独处理
t = int(lines[0].strip())
for n in lines[1:]:
    n = list(n.split(' '))
    print(int(n[0])+int(n[1]))

或者

#第一行单独处理
t = int(input())
while True:
    try:
        line = list(map(int, input().strip().split()))
        print(line[0]+line[1])
    except:
        break
  • 样例2–数字类型

输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据有多组, 如果输入为0 0则结束输入

输入
1  5
10  20
0  0
输出
6
30
while True:
    try:
        line = list(map(int, input().strip().split()))
        # line每次读到的是一行
        if line[0]==0 & line[1]==0:
            break
        else:
            print(line[0]+line[1])
    except:
        break

attention
a.split(‘_ ‘) 和a.split()效果一样,a.split(’’)报错

>>> a='a mk ll'
>>> a.split()
['a', 'mk', 'll']
>>> a.split('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> a.split(' ')
['a', 'mk', 'll']
  • 样例3–字符串类型
    输入有两行,第一行n, 第二行是n个空格隔开的字符串
输入
5
c d a bb e
输出
a bb c d e
n = int(input())
while True:
    try:
        line = list(input().split())
        line.sort()
        print(' '.join(line))
    except:
        break

attention
想要的输出是序列而不是列表

a=['a', 'b', 'c']
>>> print(a)
['a', 'b', 'c']
>>> print(' '.join(a))
a b c
>>> print(''.join(a))
abc
  • 样例4–字符串类型
    多个测试用例,每个测试用例一行。每行通过,隔开,有n个字符,n<100
输入
a,c,bb
f,dddd
nowcoder
输出
a,bb,c
dddd,f
nowcoder
while True:
    try:
        line = list(input().split(','))
        line.sort()
        print(','.join(line))
    except:
        break

参考:OJ在线编程常见输入输出练习场 https://ac.nowcoder.com/acm/contest/320#question

多线程 & 多进程

pool多线程

import multiprocessing as mp

def copy_file(name):  # 处理单个文件的函数
xxxx

pool = mp.Pool(mp.cpu_count())   # 也可以指定线程个数
# pool.map(function, list)
pool.map(copy_file, subtract_list)     

pool = multiprocessing.Pool(processes=4)  # Example: using 4 processes

    # Apply the process_func to each item in datalists using the pool
    results = []
    for result in tqdm(pool.imap_unordered(extract_vq_feature, datalists), total=len(datalists)):
        results.append(result)

    # Close the pool
    pool.close()
    pool.join()

子进程和主进程结束时间冲突会报错daemonic processes are not allowed to have children

thread多进程

参考多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
​
import os,time
def task(n):
    print('%s is runing进程号' %os.getpid())
    time.sleep(2)
    return n**2
​
​
def main():
    start_time = time.time()
    with ThreadPoolExecutor(max_workers=3) as executor:
        futures = executor.map(task, [i for i in range(10)])
    print('*'*20)
    for future in futures:
        print(future)
    print('用时共: %s second' % (time.time() - start_time))if __name__ == '__main__':
    main()

thread 并行不同的命令

  • 正常用法(case1)

import threading, time  
def doWaiting():  
    print('start waiting1: ' + time.strftime('%H:%M:%S') + "\n")
    time.sleep(3)  
    print('stop waiting1: ' + time.strftime('%H:%M:%S') + "\n")
def doWaiting1():  
    print('start waiting2: ' + time.strftime('%H:%M:%S') + "\n")   
    time.sleep(8)  
    print('stop waiting2: ', time.strftime('%H:%M:%S') + "\n")
       
thread1 = threading.Thread(target = doWaiting)  
thread1.start()  

thread2 = threading.Thread(target = doWaiting1)  
thread2.start()  

thread1.join()  ## 阻塞,所有的进程执行完再推出
thread2.join()

输出的结果:

start waiting1: 14:14:08

start waiting2: 14:14:08

stop waiting1: 14:14:11

stop waiting2:  14:14:16
  • case2:join在多个进程间起到阻塞作用
thread1 = threading.Thread(target = doWaiting)  
thread1.start()  
thread1.join()
t1 = doWaiting()  ####主进程
thread2 = threading.Thread(target = doWaiting)  
thread2.start()  
thread2.join()

执行结果:前一个进程启动join阻塞,下一个进程还没有start,就会等待这个进程结束再开始下一个进程,但是不会阻塞主进程

start waiting1: 14:18:45  //进程1

start waiting1: 14:18:45 //主进程

stop waiting1: 14:18:48
stop waiting1: 14:18:48


start waiting2: 14:18:48 //进程2

stop waiting2:  14:18:56

thread 获取返回值

  • 通过编写一个类实现
from threading import Thread


# _sum = 0


def cal_sum(begin, end):
    # global _sum
    _sum = 0
    for i in range(begin, end + 1):
        _sum += i
    return  _sum

"""重新定义带返回值的线程类"""


class MyThread(Thread):
    def __init__(self, func, args):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None


if __name__ == '__main__':
    t1 = MyThread(cal_sum, args=(1, 5))
    t2 = MyThread(cal_sum, args=(6, 10))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    res1 = t1.get_result()
    res2 = t2.get_result()

    print(res1 + res2)


输出55

json

import json
data=[{"startTime":"0.00","endTime":"5.67","content":"来关注境外疫情,澳大利亚维多利亚州州长丹尼尔·安德鲁斯七月六号宣布。 ", "userExtraContent":"女","correct":"正确"},{"startTime":"5     .69","endTime":"11.21","content":"从七号起无限期关闭与新南威尔士州的边界,以防止新冠病毒蔓延。","userExtraContent":"女 ","correct":"正确"},{"startTime":"11.24","endTime":"15.70","content":"维多利亚州近期再次暴发令人担忧的疫情,据路透社报道。","userExtraContent":"女","correct":"正确"}]

读入json格式json.loads(data),然后安装列表,读到字典,再根据key读到字典value

中文读写

在读出或写入的时候,加入encoding= 'utf-8'的注释,中间的dict/set/list都可以正常调用

字典写出和读入

dict={'李明':1, '张三':2}
f = open('test01.txt', 'w', encoding= 'utf-8')
f.write(str(dict))
f.close()

f = open('test01.txt', 'r', encoding= 'utf-8')
a = f.read()
dict = eval(a)
print(dict['李明'])

格式互转

  1. dict转str str(dict)
  2. str转dict eval(str)
  3. list转str “ ".join(list)

时间问题

  1. 以秒计数
import datetime
starttime = datetime.datetime.now()
#long running
#do something other
endtime = datetime.datetime.now()
print (endtime - starttime).seconds

pathlib

  • python3中存在pathlib比os.path模块更好用
>>> from pathlib import Path
>>> a='experiments-train/WaveRNN/mel_wavernn'
>>> a=Path(a)
>>> a
PosixPath('experiments-train/WaveRNN/mel_wavernn')
>>> a.parent----相当于os.path.dirname
PosixPath('experiments-train/WaveRNN')
>>> a.parent/'mel'  ----------相当于os.path.join()
PosixPath('experiments-train/WaveRNN/mel')
>>> a=Path('experiments-train/WaveRNN/mel_wavernn/01.txt')
>>> a.name------------相当于os.path.basename
'01.txt'



filename = Path("source_data/text_files/raw_data.txt")

print(filename.name)
# prints "raw_data.txt"

print(filename.suffix) -------------文件后缀
# prints "txt"

print(filename.stem) ------------文件裸名字
# prints "raw_data"

if not filename.exists():
    print("Oops, file doesn't exist!")
else:

matplotlib

  • plot多个子图
  • 画柱状图plt.bar(range(len(num_list)), num_list)
  • 设置图片宽高比
time = np.arange(len(src_f0_data))
fig = plt.figure()

plt.plot(time, src_f0_data,'r--',label='src_f0')
plt.plot(time, pred_f0_data,'g--',label='pred_f0')

plt.xlabel('time')
plt.ylabel('logf0')
plt.legend()
fig.set_size_inches(15, 5) ----在此基础上小幅度调整,更大的速度&加载都会很慢
plt.savefig(fig_path, format='png')
  • 设置x轴的刻度 & 调整宽高比

def plot_pitch_phn(pitch_path, phn_path, save_dir):
    pitch = np.load(pitch_path)
    pitch = pitch.reshape(-1)
    phn = open(phn_path, encoding='utf-8-sig').readlines()
    phn = [i.strip() for i in phn]
    #print(phn)
    phn = process_phn_acc_PitchLength(phn)
    #print('phn:', len(phn), 'pitch', pitch.shape)
    print(phn)
    assert len(phn)==len(pitch)
    fig_name = os.path.basename(pitch_path).split('.')[0] 
    print(fig_name)
    fig_path = os.path.join(save_dir, '%s.png'%fig_name)
    x = range(len(pitch))
    plt.figure(figsize=(20,3)) #放在前边
    plt.plot(x, pitch, label=fig_name)
    plt.xticks(x, phn)
    #plt.rcParams['figure.figsize'] = (5, 1)
    plt.legend() 
    plt.savefig(fig_path)

subprocess

  • 在python内部获取shell命令返回值
cmd = 'xxxx' #shell
result = subprocess.getstatusoutput(cmd)
print(result)

命令行

  • 忽视warning的警告信息 python -W ignore xx.py

debug小技巧

  • 异常中断
raise ValueError(error information)
  • 异常提醒但不中断
try:
	条件1
except Exception: -----except 异常类型(比如 IOError, Exception--常规错误基类)
	条件2 --------条件1异常则执行条件2

举个栗子

a=1
try:
    if a>2:
        a += 2
    else:  #### 单独的if 条件false并不会进入Exception。要在条件判断中调起;或者直接一个执行条件不合适会启动Exception
        raise Exception
except Exception:
    print('error: a is ',a)
  • print失效
    为了判断是否进入某一小段命令,有时会使用print debug,但是因为程序执行过程中错误类型不同,可能print的结果并么有打印出来,这时候可以添加 print(error information, flush=True),会避免print中的内容被冲掉没有输出;
    flush清空缓冲区内容

  • args

print('--------args----------')
for k in list(vars(args).keys()):
    print('%s: %s' % (k, vars(args)[k]))
print('--------args----------\n')

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
编写Linux巡检脚本可以大大简化系统巡检的流程,提高工作效率。下面我将介绍一下使用Python编写Linux巡检脚本的基本步骤: 1. 编写脚本头 在脚本文件的第一行添加以下内容: ``` #!/usr/bin/env python ``` 这个头告诉操作系统这是一个Python脚本文件,并且使用系统中安装的Python解释器运行它。 2. 导入需要使用的模块 巡检脚本需要使用一些模块来获取系统信息和执行命令。这些模块包括: - os:用于执行系统命令和获取系统信息。 - sys:用于获取命令行参数。 - datetime:用于获取当前时间。 在脚本文件的开头添加以下内容: ``` import os import sys import datetime ``` 3. 编写主函数 在脚本文件中编写一个主函数,用于执行巡检任务。函数中可以调用os模块的函数执行系统命令,获取系统信息。比如: ``` def main(): # 获取系统的主机名 hostname = os.popen('hostname').read().strip() print('Hostname: %s' % hostname) # 获取系统的CPU信息 cpu_info = os.popen('cat /proc/cpuinfo').read().strip() print('CPU Info: %s' % cpu_info) # 获取系统的内存信息 mem_info = os.popen('cat /proc/meminfo').read().strip() print('Memory Info: %s' % mem_info) # 获取系统的磁盘使用情况 disk_usage = os.popen('df -h').read().strip() print('Disk Usage: %s' % disk_usage) # 获取系统的网络连接状态 netstat = os.popen('netstat -an').read().strip() print('Netstat: %s' % netstat) ``` 4. 调用主函数 在脚本文件的最后添加以下内容: ``` if __name__ == '__main__': main() ``` 这段代码的作用是判断当前文件是否为主文件,如果是则执行main()函数。 5. 运行脚本 将脚本文件保存为一个.py文件,并赋予执行权限。然后在命令行中执行该文件即可。 ``` chmod +x check_system.py ./check_system.py ``` 以上就是使用Python编写Linux巡检脚本的基本步骤。根据实际需求,可以添加更多的系统巡检任务和功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值