Summary of common ways python executes external programs

  • 2020-04-02 14:43:29
  • OfStack

This example summarizes the common ways python executes external programs. Share with you for your reference. Specific analysis is as follows:

In python, we can directly call system commands or external programs through the following methods, which is easy to use

1. Execl method of OS module

Python's system method for execl is consistent with Unix's exec system call. These methods are useful when calling an external program in a child process, because the external program replaces the code of the current process and does not return.
That is, the shell process is occupied and executes the first command program for execl without returning.

2. System method using OS module

The system method creates a child to run the external program, and the method returns only the result of the external program. This method is more suitable for cases where the external program has no output. For example, in Ubuntu, use the following command to display a prompt message on the desktop.
According to my experiments, processes called with the system method return 0 at the normal end and non-0 at the exception end, regardless of the return value of the main function of the process.

3. Use the popen method of OS module

This method is useful when the output of an external program is needed. For example, when using urllib to call the Web API, the resulting data needs to be processed. An example of use is as follows:


cmd = "ssh search47c.cm2 "" + query + """
#print cmd + "<br>"
output = os.popen(cmd)
# Escape 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 (not used)

The difference between this method and popend is that while popen returns a file handle, this method returns the output of an external program as a string, which is easier to use in many cases.

I hope this article has helped you with your Python programming.


Related articles: