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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With