Ignore stderr and use return code

Ben Finney ben+python at benfinney.id.au
Sun Oct 25 22:41:24 EDT 2015


Ganesh Pal <ganesh1pal at gmail.com> writes:

> In the below code, we found that the command i.e cmd = "mount
> /filesystem1" succeeded. But the test failed due to the weaker stderr

I don't know what you mean by stderr being “weaker”.

>     def mount_me():
>         cmd = "mount /filesystem1"
>         proc = subprocess.Popen(shlex.split(cmd),
>                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>         out, err = proc.communicate()
>         if err != "":
>             logging.error("Can't run %s got %s!" % (cmd, err))
>             return False

The test ‘if err != ""’ implies you are checking *only* whether the value
is an empty string. It might be clearer if you write ‘if err’.

The error message implies the process *could not* run, but that's not
the case. If that line is reached, the process did run to completion.
The presence of output on stderr does not imply the process failed.

If instead you want to check whether the process failed, check its exit
status. The “exit status” of a process, indicating success or failure,
is “returned” by the subprocess back to Python and is available as
‘Popen.returncode’::

    EXIT_STATUS_SUCCESS = 0
    if proc.returncode != EXIT_STATUS_SUCCESS:
        logging.error(
                "Subprocess {cmd} failed with code {code:d},"
                " error output {err}".format(
                    cmd=cmd, code=proc.returncode, err=err))

> Verification:

I don't quite understand the claim of “weaker”, so I don't know what is
verified here.

>  - To handle this case, Iam planning to use return code and modify the
> above code as below ( Any other suggestions please let me know)

You may also want to think about whether raising an exception is
appropriate (rather than just returning False).

> -  Do I need to add more check to ensure the mount actually succeeds,
> may be a function?

I'd suggest relying on the exit status from the command, unless you have
good evidence it is unreliable.

-- 
 \     “When people believe that they have absolute knowledge, with no |
  `\     test in reality, this [the Auschwitz crematorium] is how they |
_o__)             behave.” —Jacob Bronowski, _The Ascent of Man_, 1973 |
Ben Finney




More information about the Python-list mailing list