Python calls shell scripts in two ways: OS. system (CMD) or OS. popen (CMD), the former returns the exit code of the script, and the latter returns the output content during script execution. The actual usage depends on your needs.
Assume that there is a shell script test. sh:
#! /Bin/bash
1. Echo "Hello world! "
2. Exit 3
OS. System (CMD ):
After the shell script is called, this method returns a 16-bit binary number. The low position is the signal number of the script to be called, and the high position is the exit status code of the script, that is, after the code of Exit 1 in the script is executed, the OS. the returned value of the system function is 1. If the returned value is 0, the return value of the function is 0 × 100. If the returned value is 0, the return value is 256.
If we need to obtain the correct return value of OS. system, we can use the displacement operation to restore the return value:
1. >>> n = OS. System (test. Sh)
2. >>> n> 8
3. >>> 3
OS. popen (CMD ):
This call method is implemented through pipelines. The function returns a file-like object with the content output by the script (which can be simply understood as the ECHO output content ). When test. Sh is called using OS. popen:
Python calls shell scripts in two ways: OS. system (CMD) or OS. popen (CMD), the former returns the exit code of the script, and the latter returns the output content during script execution. The actual usage depends on your needs.
Obviously, you should use the popen method to obtain the content by calling shell commands such as "ls ".