Stephenloky
Stephenloky

Reputation: 413

How to get the output of subprocess.check_output() python module?

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.

Upvotes: 6

Views: 7259

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121904

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.

Upvotes: 9

Related Questions