afsane
afsane

Reputation: 117

check_output doesn't works in python 3.6 while subprocess works fine

i am trying to get the output of a command in my python program by using "check_output" method. but i'm getting this error:

   out = check_output(command5 , shell=True)

File "/usr/lib64/python3.6/subprocess.py", line 336, in check_output **kwargs).stdout File "/usr/lib64/python3.6/subprocess.py", line 418, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command 'oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results-arf arf.xml /usr/share/xml/scap/ssg/content/ssg-centos7-ds.xml' returned non-zero exit status 2.

this is the part of my program that is related:

command4 = "oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results-arf arf.xml /usr/share/xml/scap/ssg/content/ssg-centos7-ds.xml"
out = check_output(command4 , shell=True)

I am sure that the command is alright because I get the results when I write:

subprocess.call(command5,shell=True)

I am using python 3.6, and work in centos 7.

any idea why the check_output can not get the result?

Upvotes: 1

Views: 5364

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122572

This is entirely normal, because the command you ran produced a non-zero exit code. It means that the command you ran is signalling that something may be wrong.

See the subprocess.check_output() documentation:

If the return code was non-zero it raises a CalledProcessError.

and

This is equivalent to:

run(..., check=True, stdout=PIPE).stdout

where the check=True flag tells run() to raise an exception when return_value is not 0:

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised.

The other function you used, subprocess.call(), does not set check=True:

Run the command described by args. Wait for command to complete, then return the returncode attribute.

This is equivalent to:

run(...).returncode

So either don't use check_output(), or catch the exception thrown, or fix the command you are running. That call() worked is no indication that the process actually produced a successful result.

For example, you could use subprocess.run() directly:

proc = subprocess.run(
    command5, shell=True, text=True
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode:
    print(f'Issue reported, exit code {proc.returncode}, stderr:')
    print(proc.stderr)
else:
    print(proc.stdout)

Upvotes: 2

Related Questions