Lua 模块的完整入门指南
一、什么是模块? 从本质上讲,Lua 模块就是存储在自己文件中的一段可复用代码。 二、创建你的第一个模块 黄金法则:模块就是一个返回(return)表的 Lua 文件。 让我们创建一个简单的数学工具模
首先,请确保你的Python环境中安装了requests
库。
pip install requests
import requests
import json
# 向ipinfo.io发送请求,不带任何IP地址,它会默认查询你自己的IP
url = "https://ipinfo.io/json"
try:
response = requests.get(url)
response.raise_for_status() # 如果请求失败 (如状态码 4xx, 5xx), 会抛出异常
# 将返回的JSON格式数据解析为Python字典
data = response.json()
print("--- 你的IP信息详情 ---")
# 为了美观,使用json.dumps进行格式化输出
print(json.dumps(data, indent=4, ensure_ascii=False))
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
运行后,你将看到类似这样的输出(信息会根据你的实际情况而变):
{
"ip": "xxx.xxx.xxx.xxx",
"hostname": "some.host.name",
"city": "xx",
"region": "xx",
"country": "CN",
"loc": "39.9042,116.4074",
"org": "xx",
"postal": "100000",
"timezone": "Asia/Shanghai",
"readme": "https://ipinfo.io/missingauth"
}
我们可以查询任何一个我们想查的公网IP,比如谷歌的公共DNS服务器 8.8.8.8
。
import requests
import json
# 定义要查询的IP地址
target_ip = "8.8.8.8"
# 构造请求URL,将IP地址拼接到URL中
url = f"https://ipinfo.io/{target_ip}/json"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
print(f"--- IP: {target_ip} 的信息详情 ---")
print(json.dumps(data, indent=4, ensure_ascii=False))
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
输出将会是:
{
"ip": "8.8.8.8",
"hostname": "dns.google",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.4056,-122.0775",
"org": "AS15169 Google LLC",
"postal": "94043",
"timezone": "America/Los_Angeles",
"readme": "https://ipinfo.io/missingauth",
"anycast": true
}
import requests
def get_ip_info(ip_address: str) -> dict | None:
"""
查询指定IP地址的详细信息。
:param ip_address: 要查询的IP地址字符串。
:return: 包含IP信息的字典,如果查询失败则返回None。
"""
url = f"https://ipinfo.io/{ip_address}/json"
try:
response = requests.get(url, timeout=5) # 增加超时设置
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"查询IP {ip_address} 时出错: {e}")
return None
# --- 使用我们封装好的函数 ---
if __name__ == "__main__":
ip_list = ["8.8.8.8", "1.1.1.1", "114.114.114.114"]
for ip in ip_list:
info = get_ip_info(ip)
if info:
country = info.get('country', 'N/A')
city = info.get('city', 'N/A')
org = info.get('org', 'N/A')
print(f"IP: {ip:<15} | Location: {country}, {city} | Organization: {org}")
点个赞,关注我获取更多实用 Python 技术干货!如果觉得有用,记得收藏本文!
字符串处理是我们日常编程中最高频的操作之一。
.strip()
- 去除首尾空白
user_input = " admin \n"
cleaned_input = user_input.strip()
print(f"清理前: '{user_input}', 清理后: '{cleaned_input}'")
# 输出:
#清理前: ' admin
#', 清理后: 'admin'
.split()
- 字符串切割
csv_line = "apple,banana,orange,grape"
fruits = csv_line.split(',')
print(fruits)
# 输出: ['apple', 'banana', 'orange', 'grape']
.join()
- 列表拼接成字符串
words = ['Hello', 'Python', 'World']
sentence = ' '.join(words)
print(sentence)
# 输出: Hello Python World
f-string (格式化字符串)
name = "张三"
age = 30
greeting = f"大家好,我叫{name},今年{age}岁了。"
print(greeting)
# 输出: 大家好,我叫张三,今年30岁了。
列表是Python中使用最广泛的数据结构,下面这几个方法是管理列表内容的基础。
.append()
- 在末尾添加元素
tasks = ['吃饭', '睡觉']
tasks.append('写代码')
print(tasks)
# 输出: ['吃饭', '睡觉', '写代码']
.sort()
- 原地排序
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort(reverse=True) # reverse=True 表示降序
print(numbers)
# 输出: [9, 5, 4, 3, 2, 1, 1]
字典通过键值对存储数据,访问速度极快。
.get()
- 安全地获取值
user_info = {'name': 'Bob', 'age': 25}
# 安全地获取职业,如果不存在,返回'未知'
job = user_info.get('job', '未知')
print(f"{user_info['name']}的职业是: {job}")
# 输出: Bob的职业是: 未知
.items()
- 遍历键值对
scores = {'数学': 95, '英语': 88, '科学': 92}
for subject, score in scores.items():
print(f"科目: {subject}, 分数: {score}")
它们不属于某个特定类型,但功能强大,适用范围极广。
len()
- 获取长度
print(len("Hello")) # 5
print(len([1, 2, 3, 4])) # 4
print(len({'a': 1, 'b': 2})) # 2
range()
- 生成数字序列
# 打印 0 到 4
for i in range(5):
print(i, end=' ')
# 输出: 0 1 2 3 4
点个赞,关注我获取更多实用 Python 技术干货!如果觉得有用,记得收藏本文!