-
Learning Directory
- Exception handling
- Defined
- Import method
- Essence
- Optimization
- Classification
0x01 Exception Handling
try: 错误语句 except: 返回错误信息 finally: 无论对错,都要执行语句
import jsondef test(): result = dict() try: print(2/0) except Exception as a: result["msg"] = "除数不能为零。" result["code"] = 403 result["data"] = [{"a": 1}, {"b": 2}] finally: return jsondumps(result)if __name__ == ‘__main__‘: print(test())
0x02 definition
- Module definition
- Logically organized (variables, functions, classes), essentially. py files
- Package definition
- From the logic quotient organization module, a directory (with __init__.py) file
0x03 Import method
- Import method
-
Import Module
import module_name # 导入单个模块import module_name1, module_name2 # 导入多个模块from module_name import * # 导入所有(不推荐)from module_name import test as newtest # 别名from module import 方法1,方法2 # 导入指定方法
-
Importing packages
import package
-
EXP Create test.py file
name = Chowdef hello():print(‘Hello Python‘)def python():print(‘Robin Chow‘)
-
EXP Import test module functions and methods
# 导入模块 import test # test即文件名 # 调用模块变量 print(test.name) # name即文件变量 # 导入方法print(test.hello()) # hello()即文件函数
0x04 Nature
- Import Essence
- Module Nature
--Execute the import file sequentially
- Package Essence
--Execute the __init__.py file under the package
* 路径搜索 ```# 查询顺序 # import module_name --> module_name.py ---> module_name.py路劲 ---> sys.path ```* 搜索路径 * Exp 把文件路径追加到python环境变量 ```import sys, osprint(sys.path)# 查找路径及文件绝对路径 x = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.paht.insert(x) # 插入环境变量路径列表```
0x05 optimization
< 待整理 >
0X06 classification
< 待整理 >
0X07 Module Explanation
-
Import Module
from datatime import datetime,timedelta print(datetime.now())
-
Method
.now # 获取当前时间 .now().year # 年 .now().month # 月 .now().day # 日 .now().hour # 时 .now().minute # 分 .now().second # 秒 .now().microsecond # 毫秒 .now().strftime("%Y-%m-%d") # 年-月-日
- Commands module
-
Linux under modules for executing Linux commands
# getstatusoutput() 返回状态码及值,成功返回状态为0,否则返回非0 a = commands.getstatusoutput(‘ifconfig‘) # 返回0及值a = commands.getstatusoutput(‘ipppconfig‘) # 返回非0及值print(a) # getoutput() 只返回状态码b = commands.getoutput(‘ifconfig‘)print(b)# win下使用import subprocessresult = subprocess.getoutput(‘ipconfig‘)print(result)
Python Basics Module