Samzz's Blog

记录折腾,年龄大了容易忘记

0%

TVbox下载:https://github.com/o0HalfLife0o/TVBoxOSC

fongmi下载:https://github.com/FongMi/Release 手机用这个,有投屏功能;(作者blog https://fongmi.eu.org/)

区别:

  1. TVBox q215613905版:TVBox OSC纯净版,支持直播回放;
  2. TVBox fongmi版:支持直播多线路、自动换源、直播倍速,手机投屏;
  3. TVBox takagen99版:TVBox OSC美化版,支持直播回放,界面美观;

影视硬核指南:https://yinghe.app/

好源:

巧技:http://pandown.pro/tvbox/tvbox.json 加载速度略慢

胖虎:https://notabug.org/imbig66/tv-spider-man/raw/master/配置/0801.json 默认七七SP无主页,切换数据源为芒果TV。搜索可以

Yoursmile7:https://agit.ai/Yoursmile7/TVBox/raw/branch/master/XC.json 主页一般,搜索很牛,带直播

木极 https://pan.tenire.com/down.php/2664dabf44e1b55919f481903a178cba.txt 首页不显示

最新接口找这里

https://xn--sss604efuw.top/

https://www.lysvc.cc/archives/category/%e5%bd%b1%e8%a7%86%e8%b5%84%e6%ba%90/tvbox%e6%8e%a5%e5%8f%a3

https://github.com/qist/tvbox

群晖Virtual Machine Manager装openwrt,映像下载地址https://openwrt.mpdn.fun:8443/?dir=lede/x86_64,用的高大全版本

已经换成istoreOS,很好用,步骤一样

新增映像

Virtual Machine Manager——映像——硬盘映像——新增——从计算机或NAS——选择刚现在的openwrt映像——下一步

导入虚拟机

Virtual Machine Manager——虚拟机——新增旁边的小三角——导入——从硬盘映像导入——名称、cpu2核内存1G够用了——下一步到底

修改ip

默认是192.168.1.1,会不会和主路由冲突?web页面账号密码admin,password

选中虚拟机——连接——

1
vi etc/config/network

在这里修改ipaddr和gateway和dns,或者登陆web修改网络——Lan,关闭dhcp

1
2
3
4
5
6
7
8
9
config interface 'lan'
option type 'bridge'
option ifname 'eth0'
option proto 'static'
option ipaddr '192.168.1.3'
option netmask '255.255.255.0'
option ip6assign '60'
option gateway '192.168.1.1'
option dns '192.168.1.1'

去openwrt的web页面概览里看看网络接口是不是全双工,不是的话虚拟机关机,操作——编辑——网络——高级(圆按钮),型号改成e1000试试。

还需要添加macvlan1

docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range 192.168.1.8/29 -o parent=ovs_eth0 macvlan1

从群晖无法访问macvlan1里的地址

创建maclan2

ip link add macvlan2 link ovs_eth0 type macvlan mode bridge
ip addr add 192.168.1.14 dev macvlan2
//1.8/29最后一位可用做桥

ip link set macvlan2 up

添加路由

ip route add 192.168.1.8 dev macvlan2
//heimdall
ip route add 192.168.1.4 dev macvlan2
//docker openwrt

群晖就能访问了

但这个接口和路由不是持久的,NAS重启就没有了,所以需要在NAS 计划任务里以root方式,触发条件为开机的自动计划任务,把上面的4条命令运行一次,这样开机后一样可以用。

1
2
转自:https://lml023.top/archives/pang-lu-you-ji-docker-rong-qi-du-li-pang-lu-you-fang-wen

突然发现N1的openwrt里的Docker里的“Freenom 域名自动续期”没有tel的通知了,更新了最新版还是不行,看日志是无法连接tel………………

恍然大悟,是路由器关闭了passwall

打开发现passwall无效,更新组件里v2ray显示无,点更新最新版是5.1.0,更新结束还是无效,ssh到/usr/bin/v2ray目录下下载了最新的解压还是无效,google了解好像是不支持5.X,找了4.X的最后一个版本 4.45.2 下载解压,显示版本了,测试也OK了,记录下

这里下载

https://github.com/v2fly/v2ray-core/releases/tag/v4.45.2

N1是arm64

这个地址https://github.com/v2fly/v2ray-core/releases/download/v4.45.2/v2ray-linux-arm64-v8a.zip

直接ssh到/usr/bin/v2ray

wget https://github.com/v2fly/v2ray-core/releases/download/v4.45.2/v2ray-linux-arm64-v8a.zip

然后

unzip v2ray-linux-arm64-v8a.zip

去组建更新看一看有没有版本,有了的话测试测试

甲骨文云的v2ray出过一次问题,换了wulabing的版本,好用,但是机器里已经有nginx并跑着东西的慎重,会覆盖掉原来的配置或文件,我就用惨遭typecho被覆盖了,放弃了过去N片文章,好在偶尔清理电脑发现以前有备份才恢复

作者github

https://github.com/wulabing/V2Ray_ws-tls_bash_onekey

安装如下:

1
wget -N --no-check-certificate -q -O install.sh "https://raw.githubusercontent.com/wulabing/V2Ray_ws-tls_bash_onekey/master/install.sh" && chmod +x install.sh && bash install.sh

集成了所有功能

基于bili此视频

安装python

安装python和pycharm,创建项目,创建文件,

print语句

1
2
3
4
print("Mosh Hamedani")  # 字符串变量,用`‘`或`“`都可以;
print('o----')
print(' ||||')
print('*'*10) # *10就是乘以搞10个,很形象

结果

1
2
3
4
Mosh Hamedani
o----
||||
**********

变量

1
2
3
4
price = 10  # 整数int
rating = 4.9 # 浮点float
name = 'Mosh' # 字符串string
is_published = False # 布尔bool,为True或False,首字母大写;

例子:定义三个变量,患者姓名、年龄、是否新患者

1
2
3
full_name = 'John Smith'
age = 20
is_new = True

input语句

1
2
name = input('What is your name? ')
print('Hi ' + name) # 字符串连接

例子:输入姓名和喜欢的颜色,输出XXX likes xxx

1
2
3
name = input('What is your name? ')
favorite_color = input('What is your favorite color? ')
print(name + ' likes ' + favorite_color)

类型转换

1
2
3
4
5
int()
float()
bool()
str()
type()

以上为转换和显示类型函数

1
2
3
birth_year = input('Birth year: ')
age = 2022 - birth_year
print(age)

运行报错

1
2
3
4
5
6
7
Birth year: 1985
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 2, in <module>
age = 2022 - birth_year
TypeError: unsupported operand type(s) for -: 'int' and 'str'

进程已结束,退出代码1

因为,输入的1985被认为是字符串变量,int减string出错,需要先将string转换成int;可使用int函数转换,可使用type函数显示类型

1
2
3
4
5
birth_year = input('Birth year: ')
print(type(birth_year))
age = 2022 - int(birth_year)
print(type(age))
print(age)

结果

1
2
3
4
Birth year: 1985
<class 'str'>
<class 'int'>
37

例子:输入磅数,输出公斤;

1
2
3
weight_lbs = input('Weight (lbs): ')
weight_kg = float(weight_lbs) * 0.45
print(weight_kg)

字符串string

单双引号组合:

1
2
course = "Python's Course for Beginners"
print(course)
1
2
course = 'Python for "Beginners"'
print(course)

三引号,实现多行字符串,比如邮件

1
2
3
4
5
6
7
8
9
10
course = """
Hi John

Here is out first email to you.

Thank you,
The support team

"""
print(course)

字符串索引,方括号的使用

1
2
3
4
5
6
7
8
9
10
11
course = 'Python for Beginners'
# 0123456789
print(course[0])
print(course[1])
print(course[-1])
print(course[-2])
print(course[0:3])
print(course[1:])
print(course[:5])
print(course[:])
print(course[1:-1])

输出

1
2
3
4
5
6
7
8
9
P
y
s
r
Pyt
ython for Beginners
Pytho
Python for Beginners
ython for Beginner

转义字符 \

格式化字符串

1
2
3
4
5
6
first = 'John'
last = 'Sminth'
message = first + ' [' + last + '] is a coder'
msg = f'{first} [{last}] is a coder'
print(message)
print(msg)

主要是f函数和花括号的使用

字符串用法

1
2
3
4
5
6
7
8
9
10
11
12
13
course = 'Python for Beginners'
print(len(course))
print(course)
print(course.upper())
print(course.lower())
print(course.title())
print(course.find('o'))
print(course.find('0'))
print(course.find('Beginners'))
print(course.replace('Beginners','Absolute Beginners'))
print(course.replace('P','J'))
print('Python' in course)
print(course)

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
20
Python for Beginners
PYTHON FOR BEGINNERS
python for beginners
Python For Beginners
4
-1
11
Python for Absolute Beginners
Jython for Beginners
True
Python for Beginners

进程已结束,退出代码0

熟悉常见函数

1
2
3
4
5
6
7
8
course = 'Python for Beginners'
len(course)
course.upper()
course.lower()
course.title()
course.find()
course.replace()
'...' in course

算术运算

1
2
3
4
5
6
7
8
9
10
11
print(10 / 3)
print(10 // 3)
print(10 % 3)
print(10 ** 3)
x = 10
x = x + 3
print(x)
x += 3
print(x)
x -= 3
print(x)

结果

1
2
3
4
5
6
7
3.3333333333333335
3
1
1000
13
16
13

运算符优先级

1
2
3
4
5
6
7
8
x = 10 +3 *2
print(x)
x = 10 +3 *2 ** 2
print(x)
x = (10 +3) *2 ** 2
print(x)
x = (2 +3) *10 - 3
print(x)

结果

1
2
3
4
16
22
52
47

数学函数

1
2
3
4
5
6
x = 2.1
print(round(x)) # 取整
print(abs(-x)) # 绝对值
import math
print(math.ceil(x)) # 向上取整
print(math.floor(x)) # 向下取整

结果

1
2
3
4
2
2.1
3
2

If语句

1
2
3
4
5
6
7
8
9
10
11
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day" )
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")

练习:

1
2
3
4
5
6
7
8
price = 1000000
has_good_credit = False

if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f"Down payment:{down_payment}")

逻辑运算符

1
2
3
4
5
6
has_high_income = True
has_good_credit = True
has_criminal_record = False

if has_high_income and has_good_credit and not has_criminal_record:
print("Eligible for loan")

and or not的使用

比较运算符

1
2
3
4
5
temperature = 30
if temperature > 30:
print("it's a hot day")
else:
print("It's not a hot day")
1
2
3
4
5
6
7
8
name = "J"
print(len(name))
if len(name) < 3:
print("Name must be at least 3 character")
elif len(name) >50:
print("Name must be a maximum of 50 character")
else:
print("Name looks good!")

(练习)重量转换

1
2
3
4
5
6
weight = input("Weight: ")
lbs_or_kg = input("(L)bs or (k)g: ")
if lbs_or_kg.upper() == "L":
print(f"You are {float(weight)*0.45} kilos")
elif lbs_or_kg.upper() == "K":
print(f"You are {float(weight)/0.45} pounds")

while循环

1
2
3
4
5
i = 1
while i <= 5:
print("*" * i)
i += 1
print("Done")

结果

1
2
3
4
5
6
*
**
***
****
*****
Done

(练习)制作猜谜游戏

1
2
3
4
5
6
7
8
9
10
11
secrets_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess =int(input("Guess: "))
guess_count += 1
if guess == secrets_number:
print("You win")
break
else:
print("Sorry,you failed")

(练习)汽车游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
command = ""
started = False
while True: #while command !=quit作用一样
command = input(">").lower()
if command == "help":
print("""
start - to start the car
stop - to stop the car
quit - to exit
""")
elif command == "start":
if started:
print("Car is already started")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("Car is already stopped.")
else:
started = False
print("Car stopped")
elif command == "quit":
break
else:
print("sorry,I don't understand that")

23 for循环

用for循环便利字符串

1
2
3
4
5
6
7
8
9
10
11
12
for item in "Python":
print(item)
for item in ["Mosh",'John','Samzz']:
print(item)
for item in [1,2,3,4]:
print(item)
for item in range(10):
print(item)
for item in range(5,10):
print(item)
for item in range(5,10,2):
print(item)

range函数语法

1
range(start, stop[, step])

参数说明:

  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

例子,计算购物车里所有产品价格综合

1
2
3
4
5
prices = [10,20,30]
total = 0
for price in prices:
total += price
print(f"Total: {total}")

24 嵌套循环

用(x,y)坐标理解循环嵌套

1
2
3
for x in range(4):
for y in range(3):
print(f"({x},{y})")

结果

1
2
3
4
5
6
7
8
9
10
11
12
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)

例子,打印x组成的F图形

1
2
3
4
5
XXXXX
XX
XXXXX
XX
XX

代码如下,这不都是初高中学basic和pascal时候的练习题么,哎………………

1
2
3
4
5
6
numbers = [5,2,5,2,2]
for x in numbers:
output = ""
for y in range(x):
output = output + "x"
print(output)

25 列表

1
2
3
4
5
6
7
8
9
10
names = ['John','Bob','Sam','Jack','lisa','Google']
print(names)
print(names[0])
print(names[1])
print(names[-1])
print(names[1:])
print(names[1:3])
print(names[:])
names[0] = 'Joh'
print(names)

看看结果感觉下

1
2
3
4
5
6
7
8
['John', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']
John
Bob
Google
['Bob', 'Sam', 'Jack', 'lisa', 'Google']
['Bob', 'Sam']
['John', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']
['Joh', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']

例子,找出列表中的最大数

1
2
3
4
5
6
numbers = [1,9,2,5,7,8,0,7,11,87,99,43,12,41]
max = numbers[0]
for number in numbers:
if number > max :
max = number
print(max)

最初编写的时候,多用了一个count函数,为了取数number[count],看了教程代码才发现,for number in出来的number就是列表里的数字,方便多了不是

26 二维列表

1
2
3
4
5
6
7
8
9
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix)
matrix[0][2] = 30
print(matrix[0][2])
print(matrix[0])

认识下二维列表和用法

二维列表的遍历

1
2
3
4
5
6
7
8
9
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in matrix:
print(row)
for item in row:
print(item)

看看结果

1
2
3
4
5
6
7
8
9
10
11
12
[1, 2, 3]
1
2
3
[4, 5, 6]
4
5
6
[7, 8, 9]
7
8
9

28 列表函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
numbers = [3,4,5,8,5,4]
numbers.append(20) # 末尾增加
print(numbers)
numbers.insert(0,10) # 指定位置插入
print(numbers)
numbers.remove(8) # 删除指定值,只能删除第一个
print(numbers)
numbers.pop() # 删除末尾
print(numbers)
print(numbers.index(3)) # 索引内容不在列表中会出错,可以用下面的in
print(50 in numbers) # 索引返回布尔值
print(numbers.count(5)) # 计数
numbers.sort() # 排序,由小到大
print(numbers)
numbers.reverse() # 反序
print(numbers)
numbers.clear() # 清除值
print(numbers)

列表去重,方法牛鼻,原本以为是嵌套循环来比较,没想到这么简单,

1
2
3
4
5
6
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)

结果

[2, 4, 6, 3, 1]

29 元组

可以理解为不能修改的列表,用(),因为不能修改所以元组的函数很少,就计数和索引;用于不需修改的值

1
2
3
4
numbers = (2,4,6,1,2)
print(numbers[1])
print(numbers.count(2)) # 计数
print(numbers.index(1)) # 索引

30 拆包

1
2
3
numbers = [1,2,3]
x,y,z = numbers
print(x,y,z) # 不是必须一起打印,单个打印也没问题

拆包的好处是,不用每次都写那么长的函数,用起来方便,另外列表和数组都可以拆包

31 字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
customer ={
"name": "Sam Zz",
"age": 36,
"is_man" : True
}
print(customer) # 注意显示方式
print(customer["name"]) # 取值,取不存在的值会报错
print(customer.get("name")) # get取值
print(customer.get("birthday")) # get取到不存在的值返回none
print(customer.get("birthday","123")) # 第二个值是默认值,当get取值存在时返回取值,当get取值不存在时返回默认值,但不改变原有字典
print(customer)
customer["name"]="Jack Smith" # 修改值
print(customer["name"])
customer["birthdate"]="Jan 1 1980" # 没有的值则为添加
print(customer)

看看运行结果

1
2
3
4
5
6
7
8
9
10
{'name': 'Sam Zz', 'age': 36, 'is_man': True}
Sam Zz
Sam Zz
None
123
{'name': 'Sam Zz', 'age': 36, 'is_man': True}
Jack Smith
{'name': 'Jack Smith', 'age': 36, 'is_man': True, 'birthdate': 'Jan 1 1980'}

进程已结束,退出代码0

例子,输入电话号码,翻译成英文,输入1234,输出One Two Three Four

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
phone = input("Phone: ")
digits_mapping = {
"1":"One",
"2":"Two",
"3":"Three",
"4":"Four",
"5":"Five",
"6":"Six",
"7":"Seven",
"8":"Eight",
"9":"Nine",
"0":"Zero"
}
output = ""
for ch in phone: # 字符串的for简直不要太好用
output += digits_mapping.get(ch,"!") + " " # 这里的!是,如果输入字符不在字典里就输出默认值!,巧妙;更巧妙的是!=后面还能加,优秀
print(output)

字符串的for简直不要太好用,过去编程这种情况还需要先 统计字符串长度x,然后从0到x循环来一个一个取数判断,累屁了,python太方便了

结果

1
2
Phone: 15612345678
One Five Six One Two Three Four Five Six Seven Eight
1
2
Phone: +86123456
! Eight Six One Two Three Four Five Six

32 表情转换器

输入表情字符变表情,例如输入Good morning sunshine :)变成Good morning sunshine 😁 ,windows版添加表情是win键+;

1
2
3
4
5
6
7
8
9
10
11
message = input(">")  # 输入的是字符串,要先分拆,按空格分割比较科学
words = message.split(' ') # 分拆函数,按照空格分割并存储为列表,牛鼻牛鼻
print(words) # 验证拆分
emojis = { # 映射表情字符的字典
":)": "😁",
":(": "😒"
}
output = ""
for word in words:
output += emojis.get(word, word) + " " # 此处又牛鼻了,get取数,不存在的值设默认值为原值
print(output)

结果

1
2
3
>Good morning sunshine :)
['Good', 'morning', 'sunshine', ':)']
Good morning sunshine 😁
1
2
3
>I am sad :(
['I', 'am', 'sad', ':(']
I am sad 😒

33 函数

1
2
3
4
5
6
7
8
9
def greet_user():  # 定义函数
print("Hi there!")
print("Welcome aboard")


# pep8的代码规范是在函数后要空两行
print("Start")
greet_user() # 调用函数
print("Finish")

重复功能定义函数,让代码更简洁

1
2
3
4
Start
Hi there!
Welcome aboard
Finish

34 参数

函数增加参数

1
2
3
4
5
6
7
8
9
def greet_user(name):  # 函数增加一个参数
print(f"Hi {name}!")
print("Welcome aboard")


print("Start")
greet_user("Samzz") # 调用函数必须带参数的值,否则出错
greet_user("Jack")
print("Finish")

增加两个参数

1
2
3
4
5
6
7
8
9
def greet_user(first_name,last_name):
print(f"Hi {first_name} {last_name}!")
print("Welcome aboard")


print("Start")
greet_user("Sam","Zz")
greet_user("Jack","Chen")
print("Finish")

此种方法为位置参数,要注意位置顺序;

结果

1
2
3
4
5
6
Start
Hi Sam Zz!
Welcome aboard
Hi Jack Chen!
Welcome aboard
Finish

35 关键字参数

1
2
3
4
5
6
7
8
9
def greet_user(first_name,last_name):
print(f"Hi {first_name} {last_name}!")
print("Welcome aboard")


print("Start")
greet_user("Sam",last_name="Zz") # 位置参数和关键字参数混合使用必须位置参数在前,如位置参数在关键字参数后会报错
greet_user(first_name="Jack",last_name="Chen") # 全部使用关键字参数
print("Finish")

关键字参数一半用于多个参数的值不好分辨时,比如三个三处都是数字,代码可读性差,增加关键字参数增加代码可读性

结果

1
2
3
4
5
6
Start
Hi Sam Zz!
Welcome aboard
Hi Jack Chen!
Welcome aboard
Finish

36 返回语句

函数需要返回值,用return即可,平方函数

1
2
3
4
5
def square(number):
return (number * number)


print(square(3))

37 创建可重复使用的函数

将32的表情转换改为函数

1
2
3
4
5
6
7
8
9
10
11
12
13
def emoji_converter (message):
words = message.split(' ')
emojis = {
":)": "😁",
":(": "😒"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output

message = input(">")
print(emoji_converter(message))

注意函数内的message变量和函数外的message变量是两个变量,名字不同亦可,各自有各自的使用区间,函数内的仅在函数内有效,函数外的仅在函数外有效;

38 例外

输入输出年龄

1
2
age = int (input('Age: '))
print(age)

如果输入不是数字,无法int,则报错

1
2
3
4
5
Age: asd
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 1, in <module>
age = int (input('Age: '))
ValueError: invalid literal for int() with base 10: 'asd'

错误类型为ValueError,正常程序中避免出错中断会把错误排除或提示出来让程序继续,所以用例外

1
2
3
4
5
try:
age = int (input('Age: '))
print(age)
except ValueError:
print('Invalid value')

结果

1
2
Age: aaa
Invalid value

延生,年龄不能为0

处理0可以用数除以0报错,例外这个报错;

1
2
3
4
5
6
try:
age = int (input('Age: '))
risk = 1/age
print(age)
except ValueError:
print('Invalid value')

结果

1
2
3
4
5
Age: 0
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 3, in <module>
risk = 1/age
ZeroDivisionError: division by zero

报错为ZeroDivisionError,把这个错误也排除掉;

这种用if语句也能判断,难道用例外更简单?

1
2
3
4
5
6
7
8
try:
age = int (input('Age: '))
risk = 1/age
print(age)
except ZeroDivisionError:
print('Age cannot be 0.')
except ValueError:
print('Invalid value.')
1
2
Age: 0
Age cannot be 0.

39 注释

1
# 一个#一个空格开始注释

老师的观念是能读懂的代码别再注释,这要拿捏了

40 类 class

1
2
3
4
5
6
7
8
9
10
11
12
class Point:
def move(self):
print('move')
def draw(self):
print('draw')


point1 = Point()
point1.x = 10
print(point1)
print(point1.x)
point1.draw()

类名首字母为大写,point1叫做实例(和云计算里面的叫法一样啊)

41 类的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def move(self):
print('move')
def draw(self):
print('draw')


point1 = Point(10,20)
print(point1.x)

大概理解了

例子,创建Person类,包含name和talk,name为构造函数

1
2
3
4
5
6
7
8
9
10
11
class Person:
def __init__(self,name):
self.name = name
def talk(self):
print(f'Hi, I am {self.name}')


john = Person('John Smith')
john.talk()
samzz = Person('Sam Zz')
samzz.talk()

创建john和samzz两个Person类的实例

结果

1
2
Hi, I am John Smith
Hi, I am Sam Zz

42 继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Mammal:
def walk(self):
print('walk')


class Dog(Mammal): # 类的继承,继承了父类的函数
def bark(self): # 继承后定义自己的函数
print('bark')


class Cat(Mammal): # 类的继承
pass

dog1 = Dog()
dog1.bark()
dog1.walk()
cat1 = Cat()
cat1.walk()

结果

1
2
3
bark
walk
walk

43 模块 module

import导入其他py文件,省略py

例子:重量单位转换文件convertres.py

1
2
3
4
5
6
def lbs_to_kg(weight):
return weight * 0.45


def kg_to_lbs(weight):
return weight / 0.45

在app.py中导入,两种导入方法,一种是全部导入,一种是导入其中的函数

1
2
3
4
5
6
7
import converters  # 全部导入

print(converters.kg_to_lbs(70)) # 使用函数的方法.

from converters import kg_to_lbs # 导入其中函数

print(kg_to_lbs(70)) # 直接使用函数

例子:将25列表里的寻找最大值变成模块

建立utils.py文件,入参为列表,返回最大值

1
2
3
4
5
6
7
def find_max(numbers):
#
max = numbers[0]
for number in numbers:
if number > max :
max = number
return (max)

app.py中导入utils,两种导入和调用函数的方法

1
2
3
4
5
6
7
8
import utils

numbers = [1, 9, 2, 5, 7, 8, 0, 7, 11, 87, 99, 43, 12, 41]
print(utils.find_max(numbers))

from utils import find_max

print(find_max(numbers))

结果

1
2
99
99

44 包

项目中新建一个包(或者创建一个文件夹、文件夹里创建一个__init__.py的文件),推荐直接创建一个包

在包里创建一个shipping.py文件

1
2
def calc_shipping():
print('calc_shipping')

在主文件app.py中导入包中的模块中的函数,三种方法

1
2
3
4
5
6
7
8
import ecommerce.shipping
ecommerce.shipping.calc_shipping()

from ecommerce.shipping import calc_shipping
calc_shipping()

from ecommerce import shipping
shipping.calc_shipping()

第一种是导入包的模块,第二种是导入包中模块中的函数,第三种是导入包中的模块,导入不同使用函数式写法不同,第二种写法最简单,三种结果都一样

1
2
3
calc_shipping
calc_shipping
calc_shipping

45 生成随机数(使用random函数)

random函数需要先导入模块,random功能强大,以下是生成随机数、生成10-20的随机数、在列表里随机选择一个三种使用

1
2
3
4
5
6
7
8
9
10
11
12
import random


for i in range(3):
print(random.random()) # 生成随机数

for i in range(3):
print(random.randint(10,20)) #10-20间随机数

numbers = ['Sam','John','Mary','Jack']
leader = random.choice(numbers) # 列表里随机选择
print(leader)

例子:掷色子,两颗,即同时生成两个随机数,用到了类和随机数函数

1
2
3
4
5
6
7
8
9
10
11
12
import random


class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second


dice = Dice()
print(dice.roll())

结果

(5, 3)

随机数,每次运行结果都不一定相同

46 使用目录

Path.glob搜索目录下的文件

1
2
3
4
from pathlib import Path

path = Path()
print(path.glob('*.py'))

运行后提示

<generator object Path.glob at 0x0000022A3E6D1D20>

为生成器对象存在内存中,需要循环遍历生成器对象,而不是打印,所以修改

1
2
3
4
5
from pathlib import Path

path = Path()
for file in path.glob('*.py'):
print(file)

或者

1
2
3
4
5
import pathlib

path = pathlib.Path()
for file in path.glob('*.py'):
print(file)

结果

1
2
3
4
app.py
converters.py
main.py
utils.py

47 pypi 和 pip

pypi.org是python官方的第三方库的仓库,供用户下载第三方库,也供开发这上传自己开发的库;

pip是python的包管理工具,全名python install packages;

视频讲了常用的处理excel的包openpyxl,安装openpyxl

cmd或者终端pip install openpyxl,稍等即可完成安装

48 项目1:使用python实现自动化(excel的操作)

先做这步,不然写完代码运行提示没有openpyxl的模块

https://blog.51cto.com/u_15080034/4160083

项目里的excel下载地址https://github.com/RagingLeviathan/HelloWorld-mosh-python/raw/master/transactions.xlsx

读excel里的值

1
2
3
4
5
6
7
8
9
10
11
12
13
import openpyxl as xl # 别名,方便使用
wb = xl.load_workbook('transactions.xlsx') # load文件
sheet = wb['Sheet1']

print(sheet.cell(1,1).value) #一种方法
cell = sheet['b1'] #单元格
cell1 = sheet.cell(1,3) #单元格
print(cell.value) #打印单元格值
print(cell1.value)
print(sheet.max_row) #最大行
print(sheet.min_row)
print(sheet.max_column) #最大列
print(sheet.min_column)

例子:打印表里price列的值,循环从c2开始(c1是表头)到c4(max_row+1,因为到max_row是2到4不包含4,所以+1)

1
2
3
4
5
6
7
8
import openpyxl as xl
wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']

# 输出表里price的值
for row in range(2,sheet.max_row+1):
cell =sheet.cell(row,3)
print(cell.value)

结果

1
2
3
5.95
6.95
7.95

列子:讲price*0.9生成新价格写入文件

1
2
3
4
5
6
7
8
9
10
11
12
import openpyxl as xl

wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

wb.save('t.xlsx') # 写入文件

运行完找到t.xlsx文件即可看到写入的内容

例子:创建图标表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import openpyxl as xl
from openpyxl.chart import BarChart,Reference

wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

values = Reference(sheet,
min_row=2,
max_row=sheet.max_row,
min_col=4,
max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart,'e2')

wb.save('t.xlsx') # 写入文件

将D2-D4的数据生成图标,写入t.xlsx中

例子:将以上程序改为函数,实现时调用函数即可做多文件的自动化执行

改造后的样子(程序处理完后在原文件里修改了)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import openpyxl as xl
from openpyxl.chart import BarChart, Reference


def process_workbook(filename):
wb = xl.load_workbook(filename)
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

values = Reference(sheet,
min_row=2,
max_row=sheet.max_row,
min_col=4,
max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'e2')

wb.save(filename) # 写入文件

process_workbook('transactions2.xlsx')

如果有一堆表格,处理的地方一样,用上面的文件遍历,再调用函数就能实现;实际问题中还是很复杂的。

后面两课机器学习和Django制作网站时长特别长,慢慢学习吧,这个十一先学这些。

有点长,慢慢写

注册AWS

首先得有AWS吧,新账户有免费套餐,刚又新注册一个,没注册过的邮箱地址+信用卡即可,信用卡双币不成功的话试试单币种,免费套餐介绍

创建S3存储桶

创建前测个速,看哪个区域比较快就在哪个区域创建S3,测速网站

如果不用域名访问,存储桶名字随便,但是域名cname访问,存储桶名字必须和域名一样

公开访问

创建过程记得打开公开访问,即取消“阻止所有公开访问”的对勾,其他没啥特别,过程不表;

启用静态托管网站

创建后,进入存储桶——权限——(最下面)静态网站托管——启用“静态网站托管”、托管类型选择”静态网站托管“、索引文件”index.html”

打开ACL

存储桶——权限——对象所有权——编辑——ACL已启用

IAM用户、权限和密钥

创建IAM用户,给予S3的权限,具体啥权限我没研究,就把S3所有权限都给了;

用户——添加权限——直接附加现有策略——搜S3选择“AmazonS3FullAccess“

安全证书——创建访问密钥,保存下来,后面aws cli会用到;

安装AWS CLI

这里下载AWS CLI安装,安装后重新打开cmd窗口,aws configure,提示输入ak和sk,就是上面下载的访问密钥,默认区域自己找,默认输出模式可以不填直接回车,这样aws cli就有了上面那个用户的密钥了,cli访问aws就有权限了;

安装 hexo-deployer-aws-s3

AWS设置好了,现在要给hexo安装 hexo-deployer-aws-s3插件,否则无法deploy到S3上;

在blog目录下,

1
npm install hexo-deployer-aws-s3 --save-dev

安装完毕还要去hexo的_config.yml里设置depoly,原来deploy是git,现在改成aws-s3,按照下面改就没问题,bucket和region当然是上面创建的bucket名和创建区域了,

1
2
3
4
5
6
7
8
9
deploy:
#type: git
#repo: https://github.com/samzzzz/samzzzz.github.io.git
#branch: master
type: aws-s3
region: ap-southeast-1
bucket: samzz.ml
prefix:

至此设置完毕;

测试下hexo d看是否部署到AWS S3成功,不成功试下hexo三联,还不行,回头再看一遍找问题吧。

题外话:同时部署到github pages和AWS S3上

没想到好办法,我是在blog文件夹下创建了两个yaml文件,分别是S3和git的,名字为_config-s3.yml_config-git.yml,写了两个批处理

git.bat

1
2
del _config.yml
copy _config-git.yml _config.yml

s3.bat

1
2
del _config.yml
copy _config-s3.yml _config.yml

最笨的办法了,就是想部署到哪里,就运行bat删除_config.yml然后把对应的配置文件复制成_config.yml

Markdown编辑器

Typora 0.11.18下载

百度网盘:https://pan.baidu.com/s/1kdXw5D5qik9E2Gq5-RJWvA 提取码:fpai

蓝奏云:https://flpai.lanzouo.com/ijEwNxkfbod

Typora 0.11.18是最后一个免费版,现在打开提示升级,丫丫的

网上找的注册表大法

win+R打开cmd输入regedit

找到 计算机\HKEY_CURRENT_USER\SOFWARE\Typora

右键Typora选择权限打开,在用户Administrator然后选择拒绝

确认,再打开Typora试试,嘿嘿

终于抽点空搞了静态博客,用的hexo,方便同步github,也方便同步AWS S3,记录下

Hexo安装

安装Node.js

Hexo基于Node.js,Node.js下载地址:Download | Node.js 下载安装包,安装Node.js会包含环境变量及npm的安装,安装后,检测Node.js是否安装成功,在命令行中输入 node -v

检测npm是否安装成功,在命令行中输入npm -v :

安装Hexo

电脑里找个地儿新建文件夹,比如hexo,然后cmd到这个文件夹下

npm安装hexo

1
npm install -g hexo-cli 
新建博客

这个blog自己起名字,就是个文件夹名

1
hexo init blog

进入到blog目录下,新建文章

1
2
3
hexo new test_my_site
hexo g
hexo s

这三个命令是新建一篇博客文章、生成网页、在本地预览

浏览器访问:

1
localhost:4000

就能看到博客了,默认主题丑了点,稍后改模板

hexo常见命令
1
2
3
npm install hexo -g #安装Hexo
npm update hexo -g #升级
hexo init #初始化博客

命令简写

1
2
3
4
hexo n "我的博客" == hexo new "我的博客" #新建文章
hexo g == hexo generate #生成
hexo s == hexo server #启动服务预览
hexo d == hexo deploy #部署

其他命令

1
2
3
4
5
hexo server #Hexo会监视文件变动并自动更新,无须重启服务器
hexo server -s #静态模式
hexo server -p 5000 #更改端口
hexo server -i 192.168.1.1 #自定义 IP
hexo clean #清除缓存,若是网页正常情况下可以忽略这条命令
更换主题

默认太丑,这里很多主题, 现在把默认主题更改成Next主题,在blog目录中cmd:

1
npm install hexo-theme-next

或者去next的github, 还有一种装法是直接git clone到themes文件夹下,要装下git

修改配置,hexo/blog/_config.yml文件里的查找并修改主题和语言,

1
2
language: zh-CN
theme: next

next主题的配置文件在hexo\blog\node_modules\hexo-theme-next\_config.yml

next主体有四种样式,上面这个配置文件修改这里,我用的第三个Pisces样式

1
2
3
4
#scheme: Muse
#scheme: Mist
scheme: Pisces
#scheme: Gemini
修改site信息
1
2
3
4
5
title:  #博客名
subtitle: #副标题
description: #描述
keywords: #关键词,设置没发现有啥变化
author: #作者
编辑文章

新建文章后在\source\_posts里就能看到文章***.md,用markdown编辑器编辑,推荐typora,现在都收费了,用最后一个免费版0.11.18并且注册表修改下可以用,专门写了一篇Markdown神器typora 0.11.18

现在本地4000端口可以访问,下篇写deploy到github上

Hexo托管到github

github注册

注册,我注册的名字是samzzzz,

然后新建库repository,如果为了github pages能访问,那此处名字必须是注册名.github.io,即samzzzz.github.io,且保持默认的Public,此时在库里上传个index.html,即可访问自己的github pages;

github pages的介绍,但具体步骤不需要按照这个,他的步骤是本地克隆,然后本地修改推到git上,咱们用hexo的deploy来推。

安装git,下载地址

安装hexo-deployer-git

1
npm install hexo-deployer-git --save

修改配置,hexo/blog/_config.yml里的deploy,注意repo后面的注释

1
2
3
4
deploy:
type: git
repo: https://github.com/samzzzz/samzzzz.github.io.git #注意这里最后需要加.git
branch: master

也可以增加token,但是上传到git上的,总觉得不安全,还是不加了

部署到github

1
hexo d

初次会弹出窗口让浏览器登陆github,目的是关联权限,至于token还是关联权限还是ssh哪个安全还未知,慢慢研究吧。

至此,以后修改md文件后两条语句即可

1
2
hexo g
hexo d

也可浓缩成一条

1
hexo g -d

ok,可以正常同步上去了

github pages使用自己域名

域名DNS里域名CNAME设为xxx.github.io

原本以为直接ok,结果不行,继续下面操作

去github的xxx.github.io库里,Settings——Pages——Custom Domain,

把已经CNAME的域名填进去,会自动检查,就ok了;

结果hexo d后又失效了,研究发现,设置域名后会在库里生成一个CNAME的文件,文件内容就是域名,一hexo d就没了

解决办法在hexo的source文件夹下创建和CNAME的文件,重新三连

1
2
3
hexo clean
hexo g
hexo d

这样,deploy后库里也有CNAME文件了,搞定!

下一篇,聊聊托管到AWS S3上咋搞。

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment