1

I have a javascript file that I run with node command in the terminal

jstest.js

var args = process.argv.slice(2);
console.log(args[0]);

var jsonata = require("jsonata");

var data = JSON.parse(args[0]);
var expression = jsonata(args[1]);
var result = expression.evaluate(data);
console.log(result);

In the terminal

node jstest3.js '{"example": [{"value": 2},{"value": 4},{"value": 5}]}' '$sum(example.value)'

Now I need to run this command through Python.So I use the subprocess module of Python to do the task

import subprocess
result = subprocess.run(['node', 'jstest3.js', '{"example": [{"value": 2},{"value": 4},{"value": 5}]}', '$sum(example.value)'])
print(result)

But I get three values as output

{"example": [{"value": 2},{"value": 4},{"value": 5}]}
11
CompletedProcess(args=['node', 'jstest3.js', '{"example": [{"value": 2},{"value": 4},{"value": 5}]}', '$sum(example.value)'], returncode=0)

But I just want the value 11.I looked up in the documentation and tried the below techniques

result = subprocess.run(['node', 'jstest3.js', '{"example": [{"value": 2},{"value": 4},{"value": 5}]}', '$sum(example.value)'], stdout=subprocess.PIPE)
print(result.stdout)

b'{"example": [{"value": 2},{"value": 4},{"value": 5}]}\n11\n'


result = subprocess.call(['node', 'jstest3.js', '{"example": [{"value": 2},{"value": 4},{"value": 5}]}', '$sum(example.value)'])
print(result)

{"example": [{"value": 2},{"value": 4},{"value": 5}]}
11
0

How do I get only the result of the expression that is 11?

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70

2 Answers2

1

You can get the output of a program in a bytes sequence by calling check_output and split it by '\n' to extract the output. To get the output only, you can slice the array to remove the args.

import subprocess

output = subprocess.check_output([
    'node', 'jstest.js',
    '{"example": [{"value": 2},{"value": 4},{"value": 5}]}',
    '$sum(example.value)'
])

# capture all the logged lines from the node process    
result = output.split(b'\n')[1:-1]
for line in result:
    print(line.decode('utf-8'))

# output
11
AlexB
  • 3,518
  • 4
  • 29
  • 46
0

You could split the result string and get the last stdout line (11) before the returncode (0)

import subprocess

output = subprocess.check_output([
    'node', 'jstest.js',
    '{"example": [{"value": 2},{"value": 4},{"value": 5}]}',
    '$sum(example.value)'
])

result = output.split('\n')[-2]
Korbinian Kuhn
  • 726
  • 4
  • 9