Python getting command line results

Keywords: Mac Python shell

Reprint link: https://blog.csdn.net/wowocpp/article/details/80775650

python gets the command line output and filters the results to find what it needs!

Here to get the MAC address and IP address of the machine as an example!

# 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()  

# Get MAC address and IP address of computer  
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))  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

Operation result:

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

E:\Program\Python>  
  • 1
  • 2
  • 3
  • 4

Several ways for python to get the return value after executing system commands

The first situation

os.system('ps aux')  
  • 1

Execute system command, no return value
The second situation

result = os.popen('ps aux')  
      res = result.read()  
      for line in res.splitlines():  
              print line  
  • 1
  • 2
  • 3
  • 4

Execute system command to obtain the result of executing system command

p = subprocess.Popen('ps aux',shell=True,stdout=subprocess.PIPE)  
   out,err = p.communicate()  
   for line in out.splitlines():  
       print line  
  • 1
  • 2
  • 3
  • 4

As above, execute system command to obtain the result of executing system command
The third situation

output = commands.getstatusoutput('ps aux')  
print  output  
  • 1
  • 2

Execute the system command and get the return value of the current function

Posted by dannymc1983 on Wed, 08 Jan 2020 07:32:35 -0800