micropython当中,如何使用 from import导入另外一个py文件中的带参数的函数def saveofflinedata(title,msg):?
时间: 2023-02-09 18:53:12 浏览: 216
在 micropython 中,可以使用 "from 文件名 import 函数名" 的语法来导入另外一个 .py 文件中的带参数的函数。具体用法示例如下:
```
from 文件名 import saveofflinedata
saveofflinedata("标题", "消息")
```
如果你希望给函数起一个别名,可以这样做:
```
from 文件名 import saveofflinedata as 保存数据
保存数据("标题", "消息")
```
值得注意的是,在 micropython 中,如果导入的文件不在当前目录下,需要指定文件的绝对路径。
相关问题
写一个python Flask销售预测系统中,有一个suanfa.py文件:先读取shuju.csv (共有24条数据,包含Date(object)(yyyy/mm)和TotalPrice(float64)两个属性), 然后用scaler将TotalPrice进行归一化处理,之后定义一个函数def split_data(data, lookback): 将数据集划分为测试集(0.2)和训练集(0.8),data_raw = data.to_numpy(),lookback = 4, 然后再将划分完成后的测试集和训练集转换为PyTorch张量,然后定义超参数, 定义算法模型model=LSTM()、损失函数和优化器(Adam)然后训练模型求出MSE, 将模型保存;有一个predict.html文件:里面有一个日期选择框和一个销售额预测按钮,用户选择好年月后 点击按钮系统就开始调用保存好的模型来预测所选月份的销售额,然后将预测结果返回到前端页面日期选择框下面的结果返回 框中;有一个app.py文件:定义路径。用flask和bootstrap、LayUI写出完整详细代码
suanfa.py:
```python
import pandas as pd
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import MinMaxScaler
# Read csv file
data = pd.read_csv('shuju.csv')
# Normalize the data
scaler = MinMaxScaler()
data['TotalPrice'] = scaler.fit_transform(data[['TotalPrice']])
# Split data into train and test sets
def split_data(data, lookback):
data_raw = data.to_numpy()
data = []
for index in range(len(data_raw) - lookback):
data.append(data_raw[index: index + lookback])
data = np.array(data)
train_size = int(len(data) * 0.8)
train_data = data[:train_size, :]
test_data = data[train_size:, :]
return train_data, test_data
train_data, test_data = split_data(data, lookback=4)
# Convert to PyTorch tensors
train_data = torch.from_numpy(train_data).type(torch.Tensor)
test_data = torch.from_numpy(test_data).type(torch.Tensor)
# Define hyperparameters
input_size = 1
hidden_size = 2
num_layers = 1
output_size = 1
learning_rate = 0.01
num_epochs = 200
# Define LSTM model
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).requires_grad_()
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).requires_grad_()
out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
out = self.fc(out[:, -1, :])
return out
model = LSTM(input_size, hidden_size, num_layers, output_size)
# Define loss function and optimizer
criterion = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
for epoch in range(num_epochs):
outputs = model(train_data)
optimizer.zero_grad()
loss = criterion(outputs, train_data[:, -1, :])
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print("Epoch: %d, loss: %1.5f" % (epoch, loss.item()))
# Save the model
torch.save(model, 'model.pt')
```
predict.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Predict sales</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='layui/css/layui.css') }}">
<script type="text/javascript" src="{{ url_for('static', filename='layui/layui.js') }}"></script>
</head>
<body>
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md-offset4 layui-col-md-4">
<h2 class="layui-text-center">Predict sales</h2>
<form class="layui-form" action="">
<div class="layui-form-item">
<label class="layui-form-label">Date</label>
<div class="layui-input-inline">
<input type="text" name="date" id="date" class="layui-input" placeholder="yyyy/mm">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-normal" onclick="predict()">Predict</button>
</div>
</div>
</form>
<div class="layui-text-center">
<h3>Predicted sales:</h3>
<h4 id="result"></h4>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function predict() {
var date = document.getElementById("date").value;
if (date === "") {
layer.msg("Please enter a date");
return;
}
var year = parseInt(date.split("/")[0]);
var month = parseInt(date.split("/")[1]);
if (isNaN(year) || isNaN(month)) {
layer.msg("Invalid date format");
return;
}
if (month < 1 || month > 12) {
layer.msg("Invalid month");
return;
}
var data = [[
[{{ test_data[-1, :][0] }}],
[{{ test_data[-2, :][0] }}],
[{{ test_data[-3, :][0] }}],
[{{ test_data[-4, :][0] }}]
]];
var model = "{{ url_for('static', filename='model.pt') }}";
$.ajax({
type: "POST",
url: "{{ url_for('predict') }}",
data: JSON.stringify({
"year": year,
"month": month,
"data": data,
"model": model
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
document.getElementById("result").innerHTML = result.predicted_sales.toFixed(2);
},
error: function(xhr, textStatus, errorThrown) {
layer.msg("Error: " + xhr.responseText);
}
});
}
</script>
</body>
</html>
```
app.py:
```python
import os
import json
import torch
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
class SalesDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
x = self.data[index, :-1]
y = self.data[index, -1]
return x, y
@app.route('/')
def index():
return render_template('predict.html')
@app.route('/predict', methods=['POST'])
def predict():
year = request.json['year']
month = request.json['month']
data = torch.from_numpy(np.array(request.json['data'])).type(torch.Tensor)
model = torch.load(request.json['model'])
predicted_sales = model(data).item()
return json.dumps({'predicted_sales': predicted_sales})
if __name__ == '__main__':
app.run(debug=True)
```
用PY写一个PC版(不是网页版)微信软件聊天辅助工具, 程序要用到import win32gui import win32con d盘中的笑话合集.TXT是一个笑话的集合,文档中每个笑话的间隔是空行 要求每间隔20分钟向指定名字的好友按指定一个笑话, 如果收到“有病”“傻”“有毛病啊”停止发送 如果收到’看过了‘’没意思‘就再发下一个笑话
以下是一个可能的解决方案:
```python
import time
import random
import win32gui
import win32con
# 微信窗口的类名和窗口名
WX_CLASS = "WeChatMainWndForPC"
WX_TITLE = "微信"
# 笑话文件的路径和发送间隔(秒)
JOKE_FILE = "D:\\笑话合集.TXT"
SEND_INTERVAL = 20 * 60
# 要发送笑话的好友和发送次数
FRIEND_NAME = "某某"
SEND_COUNT = 3
# 笑话列表和当前发送的笑话索引
jokes = []
joke_index = 0
# 读取笑话文件
with open(JOKE_FILE, "r", encoding="utf-8") as f:
joke = ""
for line in f:
if line.strip() == "":
jokes.append(joke)
joke = ""
else:
joke += line
if joke != "":
jokes.append(joke)
# 获取微信窗口句柄
hwnd = win32gui.FindWindow(WX_CLASS, WX_TITLE)
# 发送笑话的函数
def send_joke():
global joke_index
if joke_index >= len(jokes):
joke_index = 0
joke = jokes[joke_index]
joke_index += 1
win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, FRIEND_NAME)
time.sleep(1)
win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32gui.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
time.sleep(1)
win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, joke)
time.sleep(1)
win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32gui.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
print("发送笑话:", joke)
# 循环发送笑话
send_count = 0
last_send_time = time.time()
while send_count < SEND_COUNT:
# 检查是否收到停止发送的消息
if win32gui.FindWindowEx(hwnd, 0, "Edit", None) != 0:
last_msg = win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, 1024, 0)
if last_msg in ["有病", "傻", "有毛病啊"]:
print("收到停止发送的消息:", last_msg)
break
elif last_msg in ["看过了", "没意思"]:
send_joke()
last_send_time = time.time()
continue
# 检查是否到达发送间隔
if time.time() - last_send_time >= SEND_INTERVAL:
send_joke()
send_count += 1
last_send_time = time.time()
# 随机等待一段时间
time.sleep(random.randint(1, 10))
```
这个程序使用了 `win32gui` 和 `win32con` 模块来控制微信窗口,可以实现自动发送笑话的功能。具体实现过程如下:
1. 读取笑话文件,将每个笑话存储在一个列表中。
2. 获取微信窗口的句柄。
3. 定义一个发送笑话的函数,该函数会向指定的好友发送一个笑话,并更新当前发送的笑话索引。
4. 循环发送笑话,直到达到指定的发送次数或收到停止发送的消息。
5. 在每次循环中,先检查是否收到停止发送的消息,如果是则退出循环;否则检查是否到达发送间隔,如果是则调用发送笑话的函数并更新最后发送时间。
6. 在每次循环中,随机等待一段时间,以避免被微信识别为机器人。
注意,这个程序只是一个示例,实际使用时需要根据具体情况进行修改和调试。另外,自动发送消息可能会违反微信的使用协议,使用时需要自行承担风险。
阅读全文