目录
Shebang
Shebang这一语法特性由#!开头
在开头字符之后 可以有一个或数个空白字符 后接解释器的绝对路径 用于调用解释器
在直接调用脚本时 调用者会利用 Shebang 提供的信息调用相应的解释器 从而使得脚本文件的调用方式与普通的可执行文件类似
关于Shebang的更多可以介绍可以参考Shebang
/usr/bin/python --version
# Python 2.7.10
which python
# /Users/kevin/.pyenv/shims/python
python --version
# Python 3.5.2
更多关于Python版本控制工具pyenv可以参考pyenv
touch shebang.py && chmod +x shebang.py
vim shebang.py
#!/usr/bin/python
import sys
print(sys.version)
./shebang.py
# 2.7.10 (default, Aug 17 2018, 17:41:52)
# [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)]
python shebang.py
# 3.5.2 (default, Aug 27 2018, 08:43:58)
# [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)]
vim shebang.py
#!/usr/bin/env python
import sys
print(sys.version)
./shebang.py
# 3.5.2 (default, Aug 27 2018, 08:43:58)
# [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)]
/usr/bin/python shebang.py
# 2.7.10 (default, Aug 17 2018, 17:41:52)
# [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)]
Unicode
vim unicode.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = u'中文'
s = '中文'
print(type(u), type(s))
print(len(u), len(s))
print(repr(u), repr(s))
print(repr(u.encode('utf-8')))
print(repr(s.decode('utf-8')))
- Python2
python --version
# Python 2.7.12
python unicode.py
# (<type 'unicode'>, <type 'str'>)
# (2, 6)
# ("u'\\u4e2d\\u6587'", "'\\xe4\\xb8\\xad\\xe6\\x96\\x87'")
# '\xe4\xb8\xad\xe6\x96\x87'
# u'\u4e2d\u6587'
Python2:
u'str'即(unicode string) 'str'即(bytes string)
(unicode string).encode() = (bytes string)
(bytes string).decode() = (unicode string)
- Python3
python --version
# Python 3.5.2
python unicode.py
# <class 'str'> <class 'str'>
# 2 2
# '中文' '中文'
# b'\xe4\xb8\xad\xe6\x96\x87'
# Traceback (most recent call last):
# File "unicode_v3.py", line 11, in <module>
# print(s.decode('utf-8'))
# AttributeError: 'str' object has no attribute 'decode'
Python3:
u'str'和'str'都是(unicode string) b'str'才是(bytes string)
(unicode string).encode() = (bytes string)
(bytes string).decode() = (unicode string)
Module
mkdir mod dir
touch mod/__init__.py && vim mod/lib.py
def test():
print('test in lib')
vim dir/lib.py
def test():
print('test in dir')
vim module.py
from mod.lib import test
test()
from dir.lib import test
test()
- Python2
python --version
# Python 2.7.12
python module.py
# test in lib
# Traceback (most recent call last):
# File "module.py", line 4, in <module>
# from dir.lib import test
# ImportError: No module named dir.lib
- Python3
python --version
# Python 3.5.2
python module.py
# test in lib
# test in dir
有__init__.py的文件夹即是一个模块 用于声明命名空间
__main__
vim main.py
if __name__ == '__main__':
print('run in command')
else:
print('run in module')
python main.py
# run in command
__name__即当前模块名 当模块被直接运行时模块名为'__main__'
vim import_main.py
import main
python import_main.py
# run in module
网友评论