我正在尝试在python中运行一个函数,该函数从PDF文件返回我的值,我将该文件上传到用nodejs编写的控制器中,我使用PythonShell调用python函数。我希望我的控制器等待解决我的python函数,以便我可以在主体中返回这些值,以便可以在View中使用这些值。
我的问题是如何等待以及如何从函数中提取数据。
在Python.stdout.on内部,我可以在console.log中打印数据,但不能将数据返回到函数外部
该函数python是数据的示例,因为返回的函数是一个数据框。
async store({ request, response }) {
try {
if (!request.file("file")) return;
const upload = request.file("file", { size: "2mb" });
const fileName = `${Date.now()}.${upload.subtype}`;
await upload.move(Helpers.tmpPath("uploads"), {
name: fileName
});
if (!upload.moved()) {
throw upload.error();
}
const resized = await path.resolve(
__dirname,
"..",
"..",
"..",
"tmp",
"uploads",
fileName
);
let options = {
mode: "text",
pythonOptions: ["-u"],
scriptPath: path.resolve(__dirname, "..", "Service"),
args: [resized]
};
const Python = PythonShell.run("pdfRead.py", options, function(
err,
results
) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log("results: %j", results);
const data = results;
return data
});
const dataPython = await Python.stdout.on("data", data => {
console.log(`data: ${data}`);
const aux = [data];
return aux
});
return response.status(200).send(dataPython.data);
} catch (error) {
return response
.status(error.status)
.send({ error: { message: "Erro no upload de arquivo" } });
}
}
import sys
import pandas as pd
path = sys.argv[1]
def get_file(path):
data = pd.read_csv(path)
return data
print(get_file(path))
sys.stdout.flush()
参考方案
我解决了我的问题,看一下代码:D
我使用promisify将PythonShell(callback)函数转换为Promise。
async store({ request, response }) {
try {
if (!request.file("file")) return;
const upload = request.file("file", { size: "30mb" });
const fileName = `${Date.now()}.${upload.subtype}`;
await upload.move(Helpers.tmpPath("uploads"), {
name: fileName
});
if (!upload.moved()) {
throw upload.error();
}
const resized = await path.resolve(
__dirname,
"..",
"..",
"..",
"tmp",
"uploads",
fileName
);
let options = {
mode: "text",
pythonOptions: ["-u"],
scriptPath: path.resolve(__dirname, "..", "Service"),
args: [resized]
};
const readPdf = promisify(PythonShell.run);
const pdf = await readPdf("extrator.py", options);
const json = JSON.parse(pdf[0]);
const file = await File.create({
file: fileName,
name: upload.clientName,
type: upload.type,
subtype: upload.subtype,
data: json
});
return response.send(file.file);
} catch (error) {
return response
.status(error.status)
.send({ error: { message: "Erro no upload de arquivo" } });
}
Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何在python中将从PDF提取的文本格式化为json - python我已经使用pyPDF2提取了一些文本格式的发票PDF。我想将此文本文件转换为仅包含重要关键字和令牌的json文件。输出应该是这样的:#PurchaseOrder {"doctype":"PO", "orderingcompany":"Demo Company", "su…
查找字符串中的行数 - python我正在创建一个python电影播放器/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …
我怎样才能从字典的键中算出对象? - python我有这本字典:dict={"asset":[("S3","A1"),"S2",("E4","E5"),("E1","S1"),"A6","A8"], "…