About python calling cmd command:
mainly introduce two ways:
There are two ways to call the CMD command in the os module of Python : os.popen () and os.system () are called with the current process.
os.system cannot get the return value. When the operation is over, proceed to the following program.
Usage: os.system (“ipconfig”)
The execution result of import os
os.system ("ipconfig") is
as follows:
Windows IP configuration
wireless LAN adapter wireless network connection:
media status ...... : media is disconnected
with specific DNS suffix.. ...:
Ethernet adapter local connection:
connection specific DNS suffix...:
Local link IPv6 address.....: Fe80 :: e1c4: 78dd: 65a8: 7bac% 13
IPv4 address:....... ..... 192.168.180.102
Subnet Mask:....... ..... 255.255.255.0
default gateway.......... ...: 192.168.180.1
OS.popen with return value, how to get the return value.
as follows:
p = os.popen(cmd)
print p.read () #The result is a string.
import os
d = os.popen ("ipconfig")
print (d.read ())
execution results are as follows:
Windows IP configuration
wireless LAN adapter wireless network connection:
media status ... media status ... Disconnected
specific DNS suffix...:
Ethernet adapter local connection:
connect specific DNS suffix....:
Local link IPv6 address..... Fe80: : e1c4: 78dd: 65a8: 7bac% 13
IPv4 address........: 192.168.180.102
Subnet mask ....... : 255.255.255.0
default gateway .........: 192.168.180.1
Both are called with the current process, which means that they are both blocking.
Windows cmd execute multiple commands at once:
import os # os.system("ipconfig") p=os.popen('"ipconfig"&"help" ') #p=os.popen("ipconfig"+" && "+"help") #重点,1个&和2个&效果一样 print(p.read())
Three ways for python to execute linux commands
import subprocess
import os
def subprocess_():
"""
subprocess模块执行linux命令
:return:
"""
subprocess.call("ls") # 执行ls命令
def system_():
"""
system模块执行linux命令
:return:
"""
# 使用system模块执行linux命令时,如果执行的命令没有返回值res的值是256
# 如果执行的命令有返回值且成功执行,返回值是0
res = os.system("ls")
def popen_():
"""
popen模块执行linux命令。返回值是类文件对象,获取结果要采用read()或者readlines()
:return:
"""
val = os.popen('ls').read() # 执行结果包含在val中
def main():
subprocess_() # 方法1
system_() # 方法2
popen_() # 方法3
if __name__ == '__main__':
main()
Personal understanding:
Python executes the command line, there is not much difference between win and linux, it is basically common, unless the command itself is not consistent