A summary of common methods for python to execute external programs, and an external summary for python to execute
This example summarizes the common methods for executing external programs in python. Share it with you for your reference. The specific analysis is as follows:
In python, we can use the following method to directly call system commands or external programs for ease of use.
1. execl method of the OS Module
The execl System Method of Python is the same as that of the exec System of Unix. These methods are applicable when an external program is called in a child process, because the external program replaces the code of the current process and does not return.
That is to say, if the shell process is occupied, the first execl command program will be executed without returning it.
2. Use the system method of the OS Module
The system method creates a sub-process to run the external program. The method returns only the running results of the external program. This method is applicable when no external program outputs results. For example, in Ubuntu, run the following command to display a prompt message on the desktop.
According to my experiment, the process called by using the system method returns 0 if the process ends normally, and the return value is not 0 if the process ends abnormally, regardless of the return value of the main function of the process.
3. Use the popen method of the OS Module
This method is useful when an external program output result is required. For example, when using urllib to call a Web API, you need to process the obtained data. An example is as follows:
Cmd = "ssh search47c. cm2 \ "" + query + "\" "# print cmd +" <br> "output = OS. popen (cmd) # escape the special characters temp1 = output. read (). replace ('<', '<') temp2 = temp1.replace ('>', ">") temp3 = temp2.replace ('\ n', "<br> ") print temp3.replace ('/',"/")
4. Use the getoutput method of the commands module (never used)
The difference between this method and popend is that popen returns a file handle, and this method returns the output result of an external program as a string, which is more convenient to use in many cases.
I hope this article will help you with Python programming.