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) # Find MAC IP = re.findall(pat2, result) # Find IP print("MAC=%s, IP=%s" %(MAC, IP))
E:\Program\Python>del.py MAC=00-1B-77-CD-62-2B, IP=192.168.1.110 E:\Program\Python>
Several ways for python to get the return value after executing system commands
The first situation
Execute system command, no return value
The second situation
result = os.popen('ps aux') res = result.read() for line in res.splitlines(): print line
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
As above, execute system command to obtain the result of executing system command
The third situation
output = commands.getstatusoutput('ps aux') print output
Execute the system command and get the return value of the current function