python - 从 nodejs 运行 python 脚本并返回 json
问题描述
我正在使用 python-shell 运行 python 脚本。python 脚本(名为 combine.py)以 json 格式返回数据。但是代码在我的本地机器上运行良好,但在 aws 实例上运行良好。我在 pm2 日志中收到以下错误:
SyntaxError: Unexpected token / in JSON at position 0
1|app | at JSON.parse (<anonymous>)
1|app | at PythonShell.asJson (/home/ubuntu/toolCaseWebsite/node_modules/python-shell/index.js:358:21)
1|app | at /home/ubuntu/toolCaseWebsite/node_modules/python-shell/index.js:310:42
1|app | at Array.forEach (<anonymous>)
1|app | at PythonShell.recieveInternal (/home/ubuntu/toolCaseWebsite/node_modules/python-shell/index.js:306:15)
1|app | at PythonShell.receiveStderr (/home/ubuntu/toolCaseWebsite/node_modules/python-shell/index.js:290:21)
1|app | at Socket.<anonymous> (/home/ubuntu/toolCaseWebsite/node_modules/python-shell/index.js:108:18)
1|app | at Socket.emit (events.js:182:13)
1|app | at Socket.EventEmitter.emit (domain.js:442:20)
1|app | at addChunk (_stream_readable.js:279:12)
我通过首先将数据放入文件然后通过在线 json 验证器检查该数据来确保 python 脚本返回有效的 json 数据。
Nodejs(javascript文件)
var ps = require('python-shell')
noOfLines = 2
noOfClusters = 5
var options = {
mode: 'json',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: './pythonScripts/',
args: [noOfClusters, noOfLines, processingData]
}
ps.PythonShell.run('combine2.py', options, function(err, results) {
if (err) throw err
// Results is an array consisting of messages collected during executio n
//console.log(results)
// Data send to index_timeline
res.render('index_timeline', {
results: results[0]
})
fs.writeFile('myOutput.txt', JSON.stringify(results, 0, 2), err => {
// throws an error, you could also catch it here
if (err) throw err
// success case, the file was saved
console.log('File saved!')
})
})
Python 脚本(combine.py)
if __name__ == "__main__":
# getting parameters
content = sys.argv[3]
nclusters= int(sys.argv[1])
noOfLines=int(sys.argv[2])
data={"clusters":[]}
# Data Cleaning and then splitting into sentences
sentences = dataCleaning(content).split('.')#splitting sentences on basis of comma rather fullstop
sentences = list(filter(None, sentences))
temp=list()
myDict=dict()
summarizing=str()
#getting clusters
clusters = cluster_sentences(sentences, nclusters)
for cluster in range(nclusters):
for i,sentence in enumerate(clusters[cluster]):
temp.append(sentences[sentence])
summarizing+=sentences[sentence]+". "
myDict["sentences"]=list(temp)
sentence_tokens, word_tokens = tokenize_content(summarizing)
sentence_ranks = score_tokens(word_tokens, sentence_tokens)
myDict["summary"]=str(summarize(sentence_ranks, sentence_tokens,noOfLines))
data["clusters"].append(dict(myDict))
myDict.clear()
del temp[:]
summarizing=''
print(json.dumps(data))
myOutput.txt(我在上面的 txt 文件中写入的数据)
[
{
"clusters": [
{
"sentences": [
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya",
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya",
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya"
],
"summary": " Qoum & Maa Baap K Duaon Se Award Haasil Kiya. Qoum & Maa Baap K Duaon Se Award Haasil Kiya."
},
{
"sentences": [
" Mushtaq Ahmed",
" Mushtaq Ahmed",
" Mushtaq Ahmed NIJAMHAMY"
],
"summary": " Mushtaq Ahmed. Mushtaq Ahmed NIJAMHAMY."
}
]
}
]
解决方案
如果将一些非 JSON 内容写入 stdout,该内容python-shell
试图解析为 JSON,则可能会出现此错误。在 JSON 模式下,所有输出都应采用 JSON 编码,并带有用于分隔消息的回车。
尝试将您的 python 代码作为独立脚本运行,并确保没有额外的输出(例如新行)来自它。
很可能您的 python 代码正在发送一个空行字符作为输出,该节点试图解析JSON.parse("/\n")
导致此错误。
Uncaught SyntaxError: Unexpected token / in JSON at position 0
at JSON.parse
推荐阅读
- django - React 和 Django Nginx 在页面刷新时给出 404 not found 错误
- python - 从word文件生成图像,并将图像限制为文件中的文本
- reactjs - 从 6.1.x 版本更新开始,Storybook 自动构建太多
- google-sheets-api - Google SpreadSheets Api 在某些请求后阻止表格
- circuit - Logisim 如何从 ROM 内存文件向终端写入字?
- .net - 是在自托管 Azure DevOps 代理上安装 dotnet SDK,还是在构建管道中添加 UseDotNet@2 任务更好?
- java - 为什么 Windows 和 macOS/Linux 之间的 sleep(1) 的 CPU 使用率存在很大差异?
- asp.net-core - 从信息日志级别的内存缓存消息中删除响应
- windows - 清除 Flutter for Desktop (Windows) 应用程序的数据
- python - 'async_generator 不是可调用对象' FastAPI 依赖问题应用程序