【Python开发】学习笔记

118 阅读13分钟

Python开发笔记


环境

配置易用的环境

# ~/.bashrc

##############################【Python】#############################
alias python=python3
alias pip=pip3

基础语法

Number(数字)

>>> 5 + 4  # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余 
2
>>> 2 ** 5 # 乘方
32

String(字符串)

# !/usr/bin/python3

str = '123456789'

print(str)  # 输出字符串
print(str[0:-1])  # 输出第一个到倒数第二个的所有字符
print(str[0])  # 输出字符串第一个字符
print(str[2:5])  # 输出从第三个开始到第五个的字符
print(str[2:])  # 输出从第三个开始后的所有字符
print(str[1:5:2])  # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2)  # 输出字符串两次
print(str + '你好')  # 连接字符串

print('------------------------------')

print('hello\nrunoob')  # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')  # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

List(列表)

#!/usr/bin/python3

list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]
tinylist = [123, 'runoob']

print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素(但不包含第三个元素,即“[2, 3)” !!)
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表

创建二维数组

# 3列 * 5行 的二维数组:[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
list_2d = [[c for c in range(3)] for r in range(5)]  
print(list_2d)  

清空列表中的多项空值

test = ['a','','b','','c','','']
test = [i for i in test if i != '']

print(test)  # ['a', 'b', 'c']

Tuple(元组)

#!/usr/bin/python3

# 创建空元组
tup1 = ()

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )
tinytuple = (123, 'runoob')

print (tuple)             # 输出完整元组
print (tuple[0])          # 输出元组的第一个元素
print (tuple[1:3])        # 输出从第二个元素开始到第三个元素
print (tuple[2:])         # 输出从第三个元素开始的所有元素
print (tinytuple * 2)     # 输出两次元组
print (tuple + tinytuple) # 连接元组

Set(集合)

#!/usr/bin/python3

empyt_sites = set() # 创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}

print(sites)   # 输出集合,重复的元素被自动去掉

# 成员测试
if 'Runoob' in sites :
    print('Runoob 在集合中')
else :
    print('Runoob 不在集合中')


# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')

print(a)

print(a - b)     # a 和 b 的差集

print(a | b)     # a 和 b 的并集

print(a & b)     # a 和 b 的交集

print(a ^ b)     # a 和 b 中不同时存在的元素

Time(时间)

详见:www.runoob.com/python/pyth…

#!/usr/bin/env python3

import time  # 引入time模块

print("\n当前时间戳为:")
print(time.time())  # 1649047108.165695

print("\n本地时间为:")
print(time.localtime(time.time()))
# 输出:time.struct_time(tm_year=2022, tm_mon=4, tm_mday=4, tm_hour=12, tm_min=40, tm_sec=55, tm_wday=0, tm_yday=94, tm_isdst=0)

print("\n本地时间为:")
print(time.asctime(time.localtime(time.time())))
# 输出:Mon Apr  4 12:43:06 2022

print("\n格式化时间:")

# 格式化成2016-03-20 11:45:39形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Sat Mar 28 22:24:24 2016形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

# 将格式字符串转换为时间戳
print(time.mktime(time.strptime("Sat Mar 28 22:24:24 2016", "%a %b %d %H:%M:%S %Y")))

import datetime

i = datetime.datetime.now()
print("当前的日期和时间是 %s" % i)  # 2022-04-04 12:52:41.886722
print("ISO格式的日期和时间是 %s" % i.isoformat())  # 2022-04-04T12:52:41.886722
print("当前的年份是 %s" % i.year)
print("当前的月份是 %s" % i.month)
print("当前的日期是  %s" % i.day)
print("dd/mm/yyyy 格式是  %s/%s/%s" % (i.day, i.month, i.year))
print("当前小时是 %s" % i.hour)
print("当前分钟是 %s" % i.minute)
print("当前秒是  %s" % i.second)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from datetime import datetime
from datetime import date
from datetime import time as time_datetime
import time
from datetime import timedelta

# ------------------1、获得当前时间-------------#

# 得到当前时间戳
print(time.time())

# 时间戳转换为时间元组
print(time.localtime(time.time()))
print(time.gmtime(time.time()))

# 将时间元组格式化输出成字符串时间
print(time.strftime("%Y-%m-%d", time.localtime(time.time())))
print(time.strftime("%Y-%m-%d", time.gmtime(time.time())))

# 不带参数默认输出当前时间
print(time.strftime("%Y-%m-%d"))

# 通过datetime模块来实现
print(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d"))
print(datetime.now().strftime("%Y-%m-%d"))
print(datetime.today().strftime("%Y-%m-%d"))

# ------------------2、获取时间差,计算执行时间-------------#

# time 模块获取时间戳
start = time.time()
time.sleep(1)
print(time.time() - start)

# datetime模块
start = datetime.now()
time.sleep(1)
print((datetime.now() - start).seconds)

# 计算昨天的日期
print(datetime.now() - timedelta(days=1))

# 时间元组转化为时间戳
print(time.mktime(time.localtime()))  # localtime获取时间元组
print(time.mktime(time.gmtime()))  # gmtime获取时间元组,格林威治时间
print(time.mktime(datetime.now().timetuple()))  # datetime里获取时间元组

# 将时间字符串转换为时间元组
print(time.strptime("2019-07-14 11:23:33", "%Y-%m-%d %H:%M:%S"))

# 表示时间的两种方式:
# 1. 时间戳(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
# 2. 时间元组 即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同

# ------------------3、time时间模块-------------#
# time.clock方法
# 这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间
# 戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。
# (实际上是以WIN32 上QueryPerformanceCounter()
# 为基础,它比毫秒表示更为精确)

start = time.clock()
time.sleep(1)
print(time.clock() - start)

# 返回本地时间元组
print(time.localtime())
print(time.localtime(time.time()))

# 从时间元组按照格式进行格式化输出字符串
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 从时间元组转换为时间戳
print(time.mktime(time.localtime()))
print(time.mktime(time.gmtime()))
print(time.mktime(datetime.now().timetuple()))

# ------------------4、datetime时间模块-------------#
# 1.datetime.date: 是指年月日构成的日期(相当于日历)
# 2.datetime.time: 是指时分秒微秒构成的一天24小时中的具体时间(相当于手表)
# 3.datetime.datetime: 上面两个合在一起,既包含时间又包含日期
# 4.datetime.timedelta: 时间间隔对象(timedelta)。一个时间点(datetime)加上一个时间间隔(timedelta)
# 可以得到一个新的时间点(datetime)。比如今天的上午3点加上5个小时得到今天的上午8点。同理,两个时间点相减会得到一个时间间隔。
# 获取当天日期
print(date.today())

# 构造函数构造日期
print(date(2018, 1, 1))

# 格式化日期输出
print(date.today().strftime("%Y%m%d"))

# 日期转换成时间元组,其中时分秒都是0
print(date.today().timetuple())

# 按照时间戳转换为日期
print(date.fromtimestamp(time.time()))

# datetime中的time模块,构造时间
t = time_datetime(8, 11, 11)
print(t)

# 格式化时间
print(t.strftime("%H-%M-%S"))

# 新建一个datetime对象,日期为今天,既可以直接调用datetime.datetime.today(),
# 也可以直接向datetime.datetime()传值,如下:
print(datetime.today())
print(datetime.now())
print(datetime(2014, 8, 15, 8, 12, 34, 790945))

# datetime.datetime.now([tz]) 当不指定时区时,和datetime.datetime.today()是一样的结果
# 格式化时间
print(datetime.now().strftime("%H-%M-%S"))

# 返回时间元组
print(datetime.now().timetuple())
print(time.mktime(datetime.now().timetuple()))

# 数据替换
d1 = datetime(2014, 8, 15, 8, 12, 34, 790945)
print(d1.replace(year=2000))

# ------------------5、timedelta-------------#
print(datetime.today())
print(datetime.today() - timedelta(days=1))

运算符

&、&& 的区别

  • 最终结果一样。
  • & 无论左边是 false 还是 true,右边都执行。
  • && 具有短路效果,左边是 false, 右边不执行。
  • && 效率更高,项目中推荐使用。

|、|| 的区别

  • 最总的结果一样。
  • | 无论左边是false还是true,右边都会执行。
  • || 具有短路效果,左边是true,右边不执行。
  • || 效果效率更高,项目中推荐使用。

is、== 的区别

  • is 判断两个变量是否是引用同一个内存地址。

  • == 判断两个变量是否相等。

Dictionary(字典)

#!/usr/bin/python3

dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2]     = "2 - 菜鸟工具"

tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}


print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值
>>> dict_1 = dict([('a',1),('b',2),('c',3)]) #元素为元组的列表
>>> dict_1
{'a': 1, 'b': 2, 'c': 3}
>>> dict_2 = dict({('a',1),('b',2),('c',3)})#元素为元组的集合
>>> dict_2
{'b': 2, 'c': 3, 'a': 1}
>>> dict_3 = dict([['a',1],['b',2],['c',3]])#元素为列表的列表
>>> dict_3
{'a': 1, 'b': 2, 'c': 3}
>>> dict_4 = dict((('a',1),('b',2),('c',3)))#元素为元组的元组
>>> dict_4
{'a': 1, 'b': 2, 'c': 3}
# 字典推导式
p = {i:str(i) for i in range(1,5)}
print("p:",p)
'''
p: {1: '1', 2: '2', 3: '3', 4: '4'}
'''

x = ['A','B','C','D']
y = ['a','b','c','d']
n = {i:j for i,j in zip(x,y)}
print("n:",n)
'''
n: {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
'''

s = {x:x.strip() for x in ('he','she','I')}
print("s:",s)
'''
s: {'he': 'he', 'she': 'she', 'I': 'I'}
'''

类型转换

更多类型转换,见 Python数据类型转换

object 转 str

>>> s = 'RUNOOB'
>>> repr(s)
"'RUNOOB'"
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"
>>> 

浮点型str 转 int

a='2.1'  # 这是一个字符串
print(int(a))

会报错 "invalid literal for int() "

需要把字符串先转化成 float 型再转换成 int 型:

a='2.1'
print(int(float(a))) # 输出 **2**。

也可以用 eval:

>>> a = "123"
>>> type(a)
<class 'str'>
>>> b = eval(a)
>>> b
123
>>> type(b)
<class 'int'>

列表str 转 list

zifu=" ['1709020230', '1707030416', '0', '0', '0']  "
print(type(zifu))
ls =eval(zifu)
print(type(ls))

#结果是:
#<class 'str'>
#<class 'list'>
# eval 函数有将字符格式的伪 python 代码转成正常的 python 代码,特别适合于读取 config 文件和获取用户输入格式的转换:
config_args = '[(1,2,3),(4,5,6),(7,8,9)]'

# 如果不用 eval 函数的话,将 str 格式转成 python 字面格式需要如下操作
import re
config_args = re.findall("\d+",config_args)
config_args = list(map(int,img_size))
config_args = [tuple(img_size[i:i+3]) for i in range(0,len(img_size),3)]
print(config_args)

# 而用来 eval 函数仅仅需要一行代码
config_args = eval(config_args)

循环&遍历&Python 推导式

www.runoob.com/python3/pyt…

list

[表达式 for 变量 in 列表] 
[out_exp_res for out_exp in input_list]

# 或者 
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]

# 示例:
[x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]
# 他的执行顺序是:
for x in range(1,5)
    if x > 2
        for y in range(1,4)
            if y < 3
                x*y
>>> names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
>>> new_names = [name.upper()for name in names if len(name)>3]
>>> print(new_names)
['ALICE', 'JERRY', 'WENDY', 'SMITH']


>>> multiples = [i for i in range(30) if i % 3 == 0]
>>> print(multiples)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]


# 从左到右:
>>> print[(x,y)for x in [1,2]for y in [3,4]]
[(1, 3), (1, 4), (2, 3), (2, 4)]
>>> print[(x,y)for x in [1,2]for y in [3,x]]
[(1, 3), (1, 1), (2, 3), (2, 2)]


# 从右到左:
>>> print[(x,y)for x in [1,y]for y in [3,4]]
[(1, 3), (1, 4), (2, 3), (2, 4)]
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
# 同时遍历两个或更多的序列,可以使用 zip() 组合:
questions = ['name', 'quest', 'favorite color']
answers = ['qinshihuang', 'the holy', 'blue']
for q, a in zip(questions, answers):
  	# 等价的几种输出
    print('what is your %s? it is %s' % (q, a))
    print('what is your {0}? it is {1}'.format(q, a))
    print(f'what is your {q}? it is {a}')
    print('')
# 要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1
# 要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
>>> [[row[i] for row in matrix] for i in range(4)]

这个例子中的执行顺序应该为:
for i in range(4)
    for row in matrix
        row[i]
# 推导式还能加入三元表达式 进行一些更加复杂的多层判断:
array = []
for i in range(30):
    if i%3==0 and i%5==0:
        array.append("能被3-5整除")
    elif i%5==0:
        array.append("能被5整除")
    elif i%3==0:
        array.append("能被3整除")
    else:
        array.append("不能能被3-5整除")

# 等价于
array = ["能被3-5整除" if i%3==0 and i%5==0 else "能被5整除" if i%5==0 else "能被3整除" if i%3==0 else "不能被3-5整除" for i in range(30)]
print(array)

dictionary

{ key_expr: value_expr for value in collection }

或

{ key_expr: value_expr for value in collection if condition }
listdemo = ['Google','Runoob', 'Taobao']
# 将列表中各字符串值为键,各字符串的长度为值,组成键值对
>>> newdict = {key:len(key) for key in listdemo}
>>> newdict
{'Google': 6, 'Runoob': 6, 'Taobao': 6}


>>> dic = {x: x**2 for x in (2, 4, 6)}
>>> dic
{2: 4, 4: 16, 6: 36}
>>> type(dic)
<class 'dict'>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

Sequence

{ expression for item in Sequence }
或
{ expression for item in Sequence if conditional }
>>> setnew = {i**2 for i in (1,2,3)}
>>> setnew
{1, 4, 9}


>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'d', 'r'}
>>> type(a)
<class 'set'>

Tuple

(expression for item in Sequence )
或
(expression for item in Sequence if conditional )
>>> a = (x for x in range(1,10))
>>> a
<generator object <genexpr> at 0x7faf6ee20a50>  # 返回的是生成器对象

>>> tuple(a)       # 使用 tuple() 函数,可以直接将生成器对象转换成元组
(1, 2, 3, 4, 5, 6, 7, 8, 9)

print(输出)

格式化输出

详见:www.runoob.com/python/att-…

print ("我叫 %s 今年 %d 岁!" % ('小明', 10)) # '我叫 小明 今年 10 岁!'
"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序:'hello world'
"{0} {1}".format("hello", "world")  # 设置指定位置:'hello world'
"{1} {0} {1}".format("hello", "world")  # 设置指定位置:'world hello world'

print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

print("{:.2f}".format(3.1415926))  # 3.14

print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')) # This spam is absolutely horrible.

# 用元组
k=("name","mh")
v="名字:{0},name:{1}".format(*k)
# f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。
# f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去,实例如下:
>>> name = 'Runoob'
>>> f'Hello {name}'  # 替换变量
'Hello Runoob'
>>> f'{1+2}'         # 使用表达式
'3'

>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'

用了这种方式明显更简单了,不用再去判断使用 %s,还是 %d。

在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果:

>>> x = 1
>>> print(f'{x+1}')   # Python 3.6
2

>>> x = 1
>>> print(f'{x+1=}')   # Python 3.8
x+1=2

字符串输出的换行与不换行

print('hello')  # 默认输出是换行的
print('hello', end='')  # 如果要实现不换行需要在变量末尾加上 end="":

打印键值对

keyValues = {'k1': 'v1', 'k2': 'v2'}
for key, value in keyValues.items():
    print(key, value, sep=':')
    
# 或是
for key in keyValues:
    print(key, keyValues[key], sep=':')

# 输出
# k1:v1
# k2:v2

input(输入)

键盘输入

#!/usr/bin/env python3

# 直接接收输入
a = input()
print(f'a = {a}')

# 提示输入
b = input('请输入b的值:')
print(f'b = {b}')

# 接收多个值
c, d = (input("请输入2个值:").split())
print(f'c = {c}, d = {d}')

终端输入

#!/usr/bin/env python3

import sys

print('命令行参数如下:')
for i in range(len(sys.argv)):
    print(f'sys.argv[{i}] = {sys.argv[i]}')

    
# $ python 0400_module.py aaa bbb ccc --ddd --eee ff -gg -hh ii
# 命令行参数如下:
# sys.argv[0] = 0400_module.py
# sys.argv[1] = aaa
# sys.argv[2] = bbb
# sys.argv[3] = ccc
# sys.argv[4] = --ddd
# sys.argv[5] = --eee
# sys.argv[6] = ff
# sys.argv[7] = -gg
# sys.argv[8] = -hh
# sys.argv[9] = ii

import(导入)

关于 import 的小结,以 time 模块为例:

  1. 将整个模块导入,例如:import time,在引用时格式为:time.sleep(1)

  2. 将整个模块中全部函数导入,例如:from time import \*,在引用时格式为:sleep(1)

  3. 将模块中特定函数导入,例如:from time import sleep,在引用时格式为:sleep(1)

  4. 将模块换个别名,例如:import time as abc,在引用时格式为:abc.sleep(1)

Function(函数)

接收可变长参数

python中的函数还可以接收可变长参数,比如以 "*" 开头的的参数名,会将所有的参数收集到一个元组上。例如:

def test(*args):
    print(args)
    return args

print(type(test(1,2,3,4)))    #可以看见其函数的返回值是一个元组

运行

添加执行权限

原本的执行方式

$ python3 hello.py

添加执行权限

Linux/Unix系统中,你可以在脚本顶部添加以下命令让Python脚本可以像SHELL脚本一样可直接执行:

#! /usr/bin/env python3

然后修改脚本权限,使其有执行权限,命令如下:

$ chmod +x hello.py

执行以下命令:

./hello.py

urllib

基础用法

#!/usr/bin/env python3

import urllib.request
from urllib.parse import urlparse

# 示例URL
url = 'https://badges.toozhao.com/svg/01FNMTSDF7SBB1QFDXH9WJK2HC'
print(f'url = {url}')

# 解析URL
parse_result = urlparse("https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B")
print(f'parse_result = {parse_result}')

# 请求 & 异常捕获
try:
    response = urllib.request.urlopen(url)
    print(f'response = {response}')
    print(f'read = {response.read()}')
except urllib.error.URLError as e:
    print('URL 不存在')
except urllib.error.HTTPError as e:
    if e.code == 404:
        print('404')


# 执行输出如下:
# url = https://badges.toozhao.com/svg/01FNMTSDF7SBB1QFDXH9WJK2HC
# parse_result = ParseResult(scheme='https', netloc='www.runoob.com', path='/', params='', query='s=python+%E6%95%99%E7%A8%8B', fragment='')
# response = <http.client.HTTPResponse object at 0x10e2af580>
# read = b'<?xml version="1.0"?>\n<!-- Generated by SVGo -->\n<svg width="114" height="20"\n     xmlns="http://www.w3.org/2000/svg"\n     xmlns:xlink="http://www.w3.org/1999/xlink">\n<rect x="0" y="0" width="114" height="20" style="fill-opacity:1.00; fill:rgb(90,90,90); padding: 2px 5px;" />\n<rect x="0" y="0" width="74" height="20" style="fill-opacity:1.00; fill:rgb(49, 197, 83);" />\n<text x="6" y="14" style="text-anchor:start;font-size:12px;fill:white;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;" >Page Views</text>\n<text x="80" y="14" style="text-anchor:start;font-size:12px;fill:white;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;" >26</text>\n</svg>\n'
 

IDEA LiveTemplates

安装路径 参考:~/Library/Preferences/PyCharm2019.1/templates/Python-AMK.xml

<templateSet group="Python-AMK">
  <template name="amk_comments_divider" value="#######################################################################################################################&#10;&#10;" description="注释的&quot;#&quot;号分割线" toReformat="false" toShortenFQNames="true">
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_print_divider" value="print('=' * 120)" description="打印&quot;=&quot;号分割线" toReformat="false" toShortenFQNames="true">
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_from_lib_import_funs" value="from $LIB$ import $FUNCS$" description="将模块中特定函数导入,例如:from time import sleep,在引用时格式为:sleep(1)" toReformat="true" toShortenFQNames="true">
    <variable name="LIB" expression="" defaultValue="" alwaysStopAt="true" />
    <variable name="FUNCS" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_import_lib" value="import $LIB$" description="将整个模块导入,例如:import time,在引用时格式为:time.sleep(1)" toReformat="true" toShortenFQNames="true">
    <variable name="LIB" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_from_lib_import_all" value="from $LIB$ import *" description="将整个模块中全部函数导入,例如:from time import *,在引用时格式为:sleep(1)" toReformat="true" toShortenFQNames="true">
    <variable name="LIB" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_import_lib_as_custom" value="import $FUNCS$ as $CUSTOM$" description="将模块换个别名,例如:import time as abc,在引用时格式为:abc.sleep(1)。" toReformat="true" toShortenFQNames="true">
    <variable name="FUNCS" expression="" defaultValue="" alwaysStopAt="true" />
    <variable name="CUSTOM" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="amk_print_title" value="print(f' $STRING$ '.center(120, '#'))" description="居中打印标题,并用&quot;#&quot;号填充两端" toReformat="false" toShortenFQNames="true">
    <variable name="STRING" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
</templateSet>