Python calls system commands in a number of ways
1.1 Os.system (command)
Runs command commands in a child shell and returns the exit status after command execution is complete. This is actually implemented using the C standard library function system (). This function will need to reopen a terminal when executing command commands, and cannot save the execution result of command commands.
1.2 Os.popen (Command,mode)
Opens a pipeline between the command process. The return value of this function is a file object that can be read or written (as determined by mode, mode defaults to ' R '). If mode is ' r ', you can use the return value of this function to call read () to get the execution result of the command.
1.3 commands.getstatusoutput (command)
Use the Os.popen () function to execute a command command and return a tuple (Status,output) that represents the return status and execution result of the command execution. The command is executed in the same way as the {command;} 2>&1, so the output contains the console outputs or error messages. Output does not contain trailing newline characters.
2.1 Subprocess.call (["Some_command", "Some_argument", "Another_argument_or_path"])
Subprocess.call (Command,shell=true)
2.2 subprocess. Popen (command, Shell=true)
If command is not an executable file, Shell=true cannot be saved.
Using the Subprocess module, you can create new processes that can connect to the input/output/error pipelines of the new process and get the return status of the new process execution. The purpose of using the Subprocess module is to replace old functions or modules such as Os.system (), os.popen* (), commands.*, and so on.
The simplest way is to use class subprocess. Popen (command,shell=true). The Popen class has popen.stdin,popen.stdout,popen.stderr three useful properties that enable communication with the child process.
When using Os.system and Subprocess.call, there will be a flash of the cmd black box, people very uncomfortable, using the os.popen background execution, can also be able to return the execution of information
Use subprocess. Popen This method is convenient, returns a tuple type, and has a good way of handling the result
Host = ' 192.168.200.64 '
ret = subprocess. Popen ("Ping-n 1-w 1%s"% host, Shell=true, stdout=subprocess. PIPE, Stderr=subprocess. PIPE)
Print (ret)
Print (Ret.communicate ())
<subprocess. Popen Object at 0x0000000002857cc0>
(b ' \r\n\xd5\xfd\xd4\xda Ping 192.168.50.31 \xbe\xdf\xd3\xd0 \xd7\xd6\xbd\xda\xb5\xc4\xca\xfd\xbe\xdd:\r\n\xc7\ xeb\xc7\xf3\xb3\xac\xca\xb1\xa1\xa3\r\n\r\n192.168.50.31 \xb5\xc4 Ping \xcd\xb3\xbc\xc6\xd0\xc5\xcf\xa2:\r\n \xca\ XFD\XBE\XDD\XB0\XFC: \xd2\xd1\xb7\xa2\xcb\xcd = 1\xa3\xac\xd2\xd1\xbd\xd3\xca\xd5 = 0\xa3\xac\xb6\xaa\xca\xa7 = 1 (100 % \xb6\xaa\xca\xa7) \xa3\xac\r\n ', B ')
Python calls cmd, does not display cmd black box