python get command line output
Python gets the command line output results, and filters the results to find what you need!
Here is an example of obtaining the MAC address and IP address of the machine!
# 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 computer MAC 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] # 找到MAC
IP = re.findall(pat2, result)[0] # 找到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 Files \ Python > del.py
MAC=00-1B-77-CD-62-2B, IP=192.168.1.110
E:\Program\Python>
- 1
- 2
- 3
- 4
Several ways to get the return value after python executes the system command
first case
os.system ( 'ps aux' )
- 1
Execute system command, no return value
Second case
result = os.popen( 'ps aux' )
res = result . read ()
for line in res.splitlines ():
print line
- 1
- 2
- 3
- 4
Execute system commands, you can get the results of executing system commands
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
Same as above, execute the system command, you can get the result of executing the system command The
third case
output = commands.getstatusoutput('ps aux')
print output
- 1
- 2
Execute system commands and get the return value of the current function