Python implements a method to get command line output

  • 2020-06-03 07:05:04
  • OfStack

This article is an example of an Python implementation that captures command-line output. To share for your reference, specific as follows:

Python gets the command line output and filters the results to find what you need!

Here's an example of getting the native MAC address and IP address!


# coding: GB2312
import os, re
# execute command, and return the output
def execCmd(cmd):
  r = os.popen(cmd)
  text = r.read()
  r.close()
  return text
# write "data" to file-filename
def writeFile(filename, data):
  f = open(filename, "w")
  f.write(data)
  f.close()
#  Acquisition computer MAC The address and IP address 
if __name__ == '__main__':
  cmd = "ipconfig /all"
  result = execCmd(cmd)
  pat1 = "Physical Address[\. ]+: ([\w-]+)"
  pat2 = "IP Address[\. ]+: ([\.\d]+)"
  MAC = re.findall(pat1, result)[0]    #  find MAC
  IP = re.findall(pat2, result)[0]    #  find IP
  print("MAC=%s, IP=%s" %(MAC, IP))

Operation results:


E:\Program\Python>del.py
MAC=00-1B-77-CD-62-2B, IP=192.168.1.110
E:\Program\Python>

For more information about Python, please refer to Python String Manipulation Skills summary, Python Common Traversal Skills Summary, Python Data Structure and Algorithm Tutorial, Python Functions Summary and Python Introduction and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: