[Tutor] subprocess check_output

Alan Gauld alan.gauld at yahoo.co.uk
Wed Sep 20 19:13:56 EDT 2017


On 20/09/17 22:09, Derek Smith wrote:
> Why does python output this b and newline characters

Because that's what the command is returning.
The b indicates its an array of bytes (as
opposed to a unicode string)

Note the module dpocumentation for check_output() says:

"By default, this function will return the data as encoded
bytes. The actual encoding of the output data may depend
on the command being invoked, so the decoding to text
will often need to be handled at the application level."

>  how can I may it return just what I need, 
> the number 8 w/no special characters? 

You can't but you can convert the bytes into a number
if that's what you want. Just use the int() function.

> I tried str(scratch), but no go, still prints that garbage.

That just converts the sequence of bytes into a
sequence of characters.


> from subprocess import check_output
> scratch = check_output( [ cmdstr, id, pw, do, "select", "count(*)", "from", "libvolumes", "where", "status='Scratch'", "and", "library_name='TS3200'" ] )

You probably don't need to split the query into separate
words, a single string would work just as well.
Or if you want it formatted nicely a few strings:

scratch = check_output( [ cmdstr, id, pw, do,
          "select count(*) from libvolumes",
          "where status='Scratch' and library_name='TS3200'" ] )

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list