「Python」- 常见问题处理 | 场景方案 | 代码片段

该笔记将记录:在学习 Python 过程中,我们遇到的与其他语言不同的地方,以及常见问题处理;

获取操作系统相关信息 Operating System

WIP

获取网络信息

Python Get Default Gateway IP Using Netifaces: A Step Guide – Python Tutorial
python – How to get the physical interface IP address from an interface – Stack Overflow

pip install netifaces

import netifaces

获取网关设备及地址:

# gets gateway of the network
gws = netifaces.gateways()
gateway = gws['default'][netifaces.AF_INET][0]           # 默认网关地址
gateway_interface = gws['default'][netifaces.AF_INET][1] # 默认网关接口名称

获取网卡的地址:

address = netifaces.ifaddresses("interface_name")[netifaces.AF_INET][0]['addr']

常用代码

针对有些常用的代码和方法还是要整理一下的:

################################################################################
# 多行代码可以使用反斜线,一种经典的做法
################################################################################

################################################################################
# 打印字典或者数组什么的
# https://stackoverflow.com/questions/15785719/how-to-print-a-dictionary-line-by-line-in-python
################################################################################
print(json.dumps(dicObject, indent = 4, ensure_ascii=False)) # 并显示 UNICODE 字符,而不时是转义序列

################################################################################
# Python String endswith() Method
# https://www.tutorialspoint.com/python/string_endswith
################################################################################
str.startswith(suffix[, start[, end]])
str.endswith(suffix[, start[, end]])

################################################################################
# TypeError: '<' not supported between instances of 'dict' and 'dict'
# https://stackoverflow.com/questions/55695479/typeerror-not-supported-between-instances-of-dict-and-dict
################################################################################
dic.sort(key=lambda x: x[0]['name'], reverse=False)

################################################################################
# 如何在 Python3 中定义和使用常量
# https://blog.csdn.net/jieming2002/article/details/78379264
# WIP 需要定义一个类
################################################################################

################################################################################
# Python here document without newlines at top and bottom
# https://stackoverflow.com/questions/9589301/python-here-document-without-newlines-at-top-and-bottom
################################################################################
print '''
dog
cat
'''[1:-1]

print '''
dog
cat
'''.strip()

################################################################################
# How to get the date N days ago in Python
# https://www.saltycrane.com/blog/2010/10/how-get-date-n-days-ago-python/
################################################################################
from datetime import datetime, timedelta
date_N_days_ago = datetime.now() - timedelta(days=N)

################################################################################
# What's the correct way to convert bytes to a hex string in Python 3?
# https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3
################################################################################
b'\xde\xad\xbe\xef'.hex()
bytes.fromhex('deadbeef')

################################################################################
# Iterate over a dictionary in Python
# https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/
################################################################################
for state in statesAndCapitals:
    print(state)

################################################################################
# Check if a given key already exists in a dictionary
# https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary
################################################################################
# in is the intended way to test for the existence of a key in a dict.

访问数据库 Databases

该笔记将记录:在 Python 中,如何操作常见数据库;

ORM | Object Relational Mapper

SQLAlchemy
https://www.sqlalchemy.org/

database migration tool

Alembic | https://alembic.sqlalchemy.org/en/latest/

MongoDB

该部分将介绍访问 MongoDB 数据库的方法。在示例中,我们使用 PyMongo 模块:

官网:https://api.mongodb.com/python/current/api/pymongo/index.html
文档:https://api.mongodb.com/python/current/api/index.html
仓库:http://github.com/mongodb/mongo-python-driver

最常使用 MongoClient 对象:https://api.mongodb.com/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient

安装:pip3 install pymongo

命令行参数处理

import sys

print("脚本名称:", sys.argv[0])
print("参数列表:", sys.argv[1:])
print("参数个数:", len(sys.argv) - 1) # 通过 -1 移除脚本名

# 遍历所有参数
for idx, arg in enumerate(sys.argv):
    print(f"参数 {idx}: {arg}")