我正在进行一个项目,在这个项目中,我需要运行一个python脚本,这个脚本是基于选项式解决方案的。因此,在运行web服务之后,我希望得到optapy提供的解决方案作为响应。但是我刚刚收到了这条线,它是在运行解算器之后,由光带机自动生成的。16:28:03.158 [main ] INFO Solving started: time spent (186), best score (-45init/0hard/-2soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).,过了一会儿,我在控制台中收到了这个错误
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:\Users\KaryGauss\Desktop\OSPlanner Service\OSPlanner_NodeJS\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\KaryGauss\Desktop\OSPlanner Service\OSPlanner_NodeJS\node_modules\express\lib\response.js:174:12)
at Socket.<anonymous> (C:\Users\KaryGauss\Desktop\OSPlanner Service\OSPlanner_NodeJS\controllers\test.js:10:13)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23) {
code: 'ERR_HTTP_HEADERS_SENT'
}这是我的路由的控制器,在其中我调用了脚本python:
const spawn = require('child_process').spawn;
const test = (req, res) => {
const py = spawn(process.env.PYTHON, [process.env.SCRIPT]);
py.stdout.on("data", async (data) => {
//console.log(`stdout: ${data}`);
let allData = "";
allData += data;
// console.log(data.toString());
res.send(allData.toString());
});
py.stderr.on("data", (data) => {
console.log(`stderr: ${data}`);
res.send(data);
});
}
module.exports = {
test
}这是我的光学解决方案的主要功能
import sys
from domain import Reservation, ReservationSchedule, generate_problem
from constraints import define_constraints
import optapy.config
from optapy.types import Duration
from optapy import solver_factory_create
solver_config = optapy.config.solver.SolverConfig() \
.withEntityClasses(Reservation) \
.withSolutionClass(ReservationSchedule) \
.withConstraintProviderClass(define_constraints) \
.withTerminationSpentLimit(Duration.ofSeconds(30))
solver_factory = solver_factory_create(solver_config)
solver = solver_factory.buildSolver()
solution = solver.solve(generate_problem())
print(solution)发布于 2022-08-18 22:17:51
我猜正在发生的情况是,每个请求发送多个响应,这是不允许的(请参阅https://stackoverflow.com/a/48123354)。特别是,我认为正在发生的是为日志中的每一行和最终的解决方案调用您的py.stdout.on函数。
因为日志记录也是在标准输出上完成的,所以应该禁用它,这样它就不会干扰Node和Python之间的通信。这可以通过设置日志记录级别来完成,正如在用户指南的日志记录部分。中所解释的那样
import logging
logging.getLogger('optapy').setLevel(logging.ERROR)这将将记录器修改为仅在错误发生时进行日志记录,从而防止在解决期间/之后显示任何日志行(除非发生错误)。
https://stackoverflow.com/questions/73405782
复制相似问题