从nodejs运行python脚本并返回json

时间:2019-04-15 08:08:26

标签: python node.js json

我正在使用python-shell运行python脚本。 python脚本(名为Combine.py)以json格式返回数据。但是代码在我的本地计算机上工作正常,但在aws实例上工作不正常。我在pm2日志中收到以下错误:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<p><b>msg from parent:</b> {{msg}}</p>
  <greeting v-if="!isDead" @hook:destroyed="changeMsg()"></greeting>
</div>

我先通过将数据放入文件中,然后通过在线json验证器检查该数据来确保python脚本返回有效的json数据。

Nodejs(JavaScript文件)

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)

Python脚本(combine.py)

  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!')
    })
  })

myOutput.txt(我在上面的txt文件中写入的数据)

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))

2 个答案:

答案 0 :(得分:1)

如果将某些非JSON内容写入标准输出(python-shell试图将其解析为JSON),则可能会发生此错误。在JSON模式下,所有输出均应进行JSON编码,并带有回车符以分隔消息。

尝试将Python代码作为独立脚本运行,并确保没有多余的输出(例如新行)。

您的python代码很可能发送空行char作为输出,该节点试图将其解析为JSON.parse("/\n")导致此错误。

Uncaught SyntaxError: Unexpected token / in JSON at position 0
    at JSON.parse 

答案 1 :(得分:0)

非常感谢。问题是有些相似之处。服务器正在返回有关某些模块将来折旧的警告。这就是为什么python-shell无法获取json格式的数据的原因。通过添加命令行选项来忽略警告,我也能够在服务器上运行此代码