python-shell
python-shell copied to clipboard
Uncaught error when parsing JSON
I'm calling a python script that outputs JSON if everything goes right, but outputs an error message otherwise. When using {mode: 'json'}, a JSON parsing error is thrown instead of being returned through the callback.
SyntaxError: Unexpected token o
at Object.parse (native)
at asJson (...\node_modules\python-shell\index.js:142:21)
at ...\node_modules\python-shell\index.js:232:35
at Array.forEach (native)
at PythonShell.receive (...\node_modules\python-shell\index.js:231:11)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at Pipe.onread (net.js:531:20)
It means non-JSON content got written to stdout, which python-shell tried to parse as JSON. In JSON mode, all output should be JSON-encoded, with carriage returns for separating messages.
Yes, I know the cause. But the fact that the program didn't output JSON should be seen as an error in my opinion.
Right, it should be handled better. I'll keep that in mind for a future version.
I had this issue which was slowing down my development and figured out that I could use stderrParser to transform the errors to valid JSON. By doing this I got the errors come out as messages and can be caught using the pyshell.on('message', ...) and pyshell.end(...) callbacks.
Workaround:
const options = {
mode: 'json',
stderrParser: (line) => JSON.stringify(line),
};
This works for now, but it seems strange that this is needed. Shouldn't python-shell do this internally? As it is now it feels like using mode: 'json' is broken.