6

I'm trying to get information from a Command Prompt (CMD - Windows ) in python, using the module subprocess like this :

ipconfig = subprocess.check_output("ipconfig")
print(ipconfig)

The result is:

b'\r\nWindows IP Configuration\r\n\r\n\r\nEthernet adapter Local Area Connect:\r\n\r\n   Connection-specific DNS Suffix  . : XX.XXX\r\n   IPv4 address. . . . . . . . . . . : XXXXXXXXX\r\n   Subnet Mask . . . . . . . . . . . : XXXXXXXXXX\r\n   Default Gateway . . . . . . . . . : XXXXXX\r\n'

I've read the documentation on module subprocess but I didn't find anything that fits my problem.

I need this information in a nice formatted string ... not like that, what could I do?

(I Think the problem here is a string format, but if you have tips for getting a nice output without needing of string formatting, I appreciate)

I know that I can get IP address with socket module, but I'm just giving an example.

2
  • What kind of "nice formatting" do you want? What you have there is the literal output of ipconfig, which is formatted, to start with... Commented Jan 31, 2014 at 17:51
  • The one which @martijn answered, the 'real' result of prompt. Commented Jan 31, 2014 at 18:16

1 Answer 1

9

You are printing a bytes string value, and print() turned that into a unicode string using repr(). You want to decode the value to unicode instead:

import sys

print(ipconfig.decode(sys.stdout.encoding))

This uses the encoding of the console to interpret the command output.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! That works perfectly, I will stude the decode,stdout,encoding methods ... Thank you very much
Why did you prefer sys.stdout.encoding over sys.getfilesystemencoding() ? sys.stdout can be None in some cases.
@Kentzo: sys.getfilesystemencoding() is the wrong codec; your file system and your terminal do not have to use the same encoding..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.