2

$ jsonlint -cq /home/test/notokay1.json

The above command has exit value 1 and the below output

/home/notokay1.json: line 6, col 1, found: 'EOF' - expected: '}', ','.

How can i capture both in Python.

Munai Das Udasin
  • 510
  • 1
  • 10
  • 24

3 Answers3

3

Use subprocess.Popen:

import subprocess

p = subprocess.Popen('jsonlint -cq /home/test/notokay1.json'.split(),
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
out, err = p.communicate()

print "Standard Output:", out
print "Standard Error Output:", err
print "Return Code:", p.returncode
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

You can use the subprocess module, more specifically the check_output method.

Suppose that you have a file called test.bash with the following contents:

echo "Hi"
exit 1

To capture both the exit code and the output you could do something like this:

# test.py file
import subprocess

exitCode = 0
output = ""
try:
    output = subprocess.check_output(["bash", "test.bash"]) # get only ouput
except subprocess.CalledProcessError as e:
    # get output and exit code
    exitCode = e.returncode
    output = e.output

print(output, exitCode)

Which outputs:

bash-4.2$ python test.py 
('Hi\n', 1)

You just need to adapt this to your problem.

BrunoRB
  • 889
  • 8
  • 14
-2

I beleive this is what you're looking for:

$ jsonlint -cq /home/test/notokay1.json > stdout.txt; echo $? > stderr.txt

you can then use python's built in file I/O to read stdout.txt and stderr.txt

refrence: http://www.tldp.org/LDP/abs/html/io-redirection.html

SIGSTACKFAULT
  • 919
  • 1
  • 12
  • 31