Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 700
Stephenloky Avatar asked Jan 31 '14 17:01

Stephenloky


People also ask

What does Python subprocess Popen return?

Popen Function The function should return a pointer to a stream that may be used to read from or write to the pipe while also creating a pipe between the calling application and the executed command. Immediately after starting, the Popen function returns data, and it does not wait for the subprocess to finish.

What is the output of subprocess Check_output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

What does Check_output return?

New in version 3.3. Subclass of SubprocessError , raised when a process run by check_call() , check_output() , or run() (with check=True ) returns a non-zero exit status. Exit status of the child process.

How do I get output to run from subprocess?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

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.

like image 114
Martijn Pieters Avatar answered Sep 20 '22 00:09

Martijn Pieters