The examples in this paper summarize the common methods used by Python to execute external programs. Share to everyone for your reference. The specific analysis is as follows:
In Python we can call system commands or external programs directly using the following method, which is convenient to use
1. Execl Method of OS module
Python's execl system approach is consistent with the UNIX exec system call. These methods apply to situations in which an external program is called in a child process, because the external program replaces the current process's code and does not return.
In other words, this shell process is occupied and will execute the first EXECL command program without returning.
2. System method using OS module
The system method creates a child process that runs an external program that returns only the results of the external program's operation. This method is more suitable for cases where external programs do not have output results. For example, under Ubuntu, use the following command to display a message on the desktop.
According to my experiment, the process called by the system method returns 0 normally, and the end of the exception returns non 0, not depending on the return value of the process main function.
3. Popen method using OS module
This method is useful when you need to get the output from an external program. For example, when using Urllib to invoke the Web API, the resulting data needs to be processed. An example of use is as follows:
cmd = "ssh search47c.cm2 \" "+ Query +" \ "#print cmd +"
"Output = Os.popen (cmd) #对特殊字符进行转义temp1 = Output.read (). Replace (' < ', ' < ') Temp2 = Temp1.replace (' > '," > ") Temp3 = Temp2.replace (' \ n ', "
") Print temp3.replace ('/',"/")
4, using the Commands module GetOutput method (no use)
The difference between this method and Popend is that Popen returns a file handle, and this method returns the output of the external program as a string, which in many cases is easier to use.
Hopefully this article will help you with Python programming.