LOADING STUFF...

Python黑魔法手册 2.0 文档第一章【3-6】

Python2年前 (2022)更新 safedragon
84 0

Python黑魔法手册 2.0

第一章:魔法冷知识【3-6】

1.3 可直接运行的 zip 包

我们可以经常看到有 Python 包,居然可以以 zip 包进行发布,并且可以不用解压直接使用。
这与大多数人的认识的 Python 包格式不一样,正常人认为 Python 包的格式要嘛 是 egg,要
嘛是whl 格式。
那么这个zip 是如何制作的呢,请看下面的示例。

[root@localhost ~]# ls -l demo
total 8
-rw-r--r-- 1 root root 30 May 8 19:27 calc.py
-rw-r--r-- 1 root root 35 May 8 19:33 __main__.py
[root@localhost ~]#
[root@localhost ~]# cat demo/__main__.py
import calc
print(calc.add(2, 3))
[root@localhost ~]#
[root@localhost ~]# cat demo/calc.py
def add(x, y):
 return x+y
[root@localhost ~]#
[root@localhost ~]# python -m zipfile -c demo.zip demo/*
[root@localhost ~]#

制作完成后,我们可以执行用 python 去执行它

[root@localhost ~]# python demo.zip
5
[root@localhost ~]#

 

1.4 反斜杠的倔强: 不写最后

` 在 Python 中的用法主要有两种
1、在行尾时,用做续行符

[root@localhost ~]$ cat demo.py
print("hello "\
 "world")
[root@localhost ~]$
[root@localhost ~]$ python demo.py
hello world

2、在字符串中,用做转义字符,可以将普通字符转化为有特殊含义的字符。

>>> str1='\nhello' #换行
>>> print(str1)
hello
>>> str2='\thello' #tab
>>> print(str2)
 hello

但是如果你用单 \ 结尾是会报语法错误的

>>> str3="\"
 File "<stdin>", line 1
 str3="\"
 ^
SyntaxError: EOL while scanning string literal

就算你指定它是个 raw 字符串,也不行。

>>> str3=r"\"
 File "<stdin>", line 1
 str3=r"\"
 ^
SyntaxError: EOL while scanning string literal

1.5 如何修改解释器提示符

这个当做今天的一个小彩蛋吧。应该算是比较冷门的,估计知道的人很少了吧。
正常情况下,我们在 终端下 执行Python 命令是这样的。

>>> for i in range(2):
... print (i)
...
0
1

你是否想过 >>> 这两个提示符也是可以修改的呢?

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>>
>>> sys.ps2 = '---------------- '
>>> sys.ps1 = 'Python编程时光>>>'
Python编程时光>>>for i in range(2):
---------------- print (i)
----------------
0
1

1.6 简洁而优雅的链式比较

先给你看一个示例:

>>> False == False == True
False

你知道这个表达式为什么会会返回 False 吗?
它的运行原理与下面这个类似,是不是有点头绪了:

if 80 < score <= 90:
 print("成绩良好")

如果你还是不明白,那我再给你整个第一个例子的等价写法。

>>> False == False and False == True
False

这个用法叫做链式比较。

© 版权声明

相关文章

暂无评论

暂无评论...