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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

Sorry check_call does only check the returncode, therefore check_output is the correct function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.