0

I'm trying to print out an output from this line of code:

subprocess.check_output('cmd.exe /K cmd',shell=False) 

But the output is something like this

**Microsoft Windows [Version 6.3.9600]\r\n(c) 2013 Microsoft Corporation. All rights reserved.\r\n\r\nC:\\Users\\19leungc8\\Desktop>\r\nC:\\Users\\19leungc8\\Desktop>** 

Instead of this :

**Microsoft Windows [Version 6.3.9600]** **(c) 2013 Microsoft Corporation. All rights reserved.** 

I'll supply more information if required.

0

2 Answers 2

2

You need not to worry about it. \n in string means new line in the string. If you will print the content of check_output(), you will see the \n replaced with new line in the console. For example:

>>> my_text = "1234\n\n1234" >>> my_text '1234\n\n1234' # ^ value of `my_text` holds `\n` # on printing the `my_text`, `\n` is replaced with new line >>> print(my_text) 1234 1234 

In your case, you should do it like:

my_output = subprocess.check_output(...) print(my_output) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response. Could you read my response below your post?
1

As the documentation for subprocess.check_output explains:

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.

So what you get back is a bytes object that contains the output of your command as encoded bytes. You can see this when you print the object; bytes literals have a b in front of the quotes both when printed and when the repr is printed:

>>> x = b'foo bar' >>> print(x) b'foo bar' >>> x # basically the same as print(repr(x)) b'foo bar' 

In order to get a proper string out of this, you need to decode the bytes object using bytes.decode(). Note that in order to decode bytes into a string, you need to know what encoding the data is encoded as. Very commonly, this will be utf-8 in which case you do not need to pass any argument to it:

>>> x.decode() 'foo bar' >>> print(x.decode()) foo bar 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.