Sometimes it is necessary to invoke the shell command directly to complete some simple operations, such as mount a file system. So how do we use Python to invoke the Linux shell command? Here are a few common ways to do this:
1. OS module
1.1. The Exec method family of the OS module
The exec system method of Python 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. (This looks at some help (OS)--and search "exec" for an introduction, but not too understanding how to use)
1.2. System methods for OS modules
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.
[Python]View Plaincopy
- >>> import OS
- >>> Os.system ("echo \" Hello world\ ") # call an echo command directly using Os.system
- Hello World —————— > Print command results
- 0 —————— > What's this? return value?
- >>> val = Os.system ("Ls-al | grep \ "Log\" ") # Receive return value using Val
- -rw-r--r-- 1 root root 6030829 Dec :—————— > Only command results are printed at this time
- >>> Print Val
- 0 —————— > Note that when the command is running normally, the return value is 0
- >>> val = Os.system ("Ls-al | grep \ "Log1\" ")
- >>> Print Val
- —————— > Use Os.system to invoke a command that returns no results, with a return value of 256~
- >>>
Note: As mentioned above, this method of fat will result in the external program, that is, the result of Os.system, so if you want to receive the return value of the command, then look down ~
1.3. Popen Methods for OS modules
This method is useful when you need to get the output from an external program, returning a class file object that calls the read () or ReadLines () method of the object to read the output. For example, when using Urllib to invoke the Web API, the resulting data needs to be processed. Os.popen (CMD) to get the output of the command, just call the next read () or readlines (), such as A=os.popen (CMD). Read ()
[Python]View Plaincopy
- >>> Os.popen (' ls-lt ') # call Os.popen (CMD) does not get the result we want
- <open file ' ls-lt ', mode ' R ' at 0xb7585ee8>
- >>> Print Os.popen (' ls-lt '). Read () # Call the Read () method to get the result of the command
- Total 6064
- -rwxr-xr-x 1 Long Long 5 :hello.sh
- -rw-r--r-- 1 Long long 147 Jan 5 :Makefile
- Drwxr-xr-x 3 long 4096 Jan 2 :notoginseng test
- -rw-r--r-- 1 root root 6030829 Dec : +log
- Drwxr-xr-x 2 long 4096 Dec :pip_build_long
- DRWX------ 2 DEBIAN-GDM debian-gdm 4096 Dec :pulse-gylj5el24gu9
- DRWX------ 2 long 4096 Jan 1 1970 Orbit-long
- >>> val = os.popen (' ls-lt '). Read () # Use variables to receive command return values
- >>> if "log" in Val: # We can use in to judge that there is a string in the return value of the wood
- ... print "Haha,there is the log"
- ... Else:
- ... print "No,not Happy"
- ...
- Haha,there is the log
2. Commands Module
Using the GetOutput method of the commands module, this method differs from Popend in that Popen returns a class file object, and this method returns the output of the external program as a string, which in many cases is more convenient to use.
Main methods:
* Commands.getstatusoutput (CMD) return (status, output)
* Commands.getoutput (CMD) returns only output results
* Commands.getstatus (file) returns the execution result string for Ls-ld file, called GetOutput, and is not recommended for use with this method
[Python]View Plaincopy
- [Email protected]:/tmp/tests$ python
- Python 2.7. 3 (Default, Jan 2 , from: :)
- [GCC 4.7. 2] on linux2
- Type "Help", "copyright", "credits" or "license" for more information.
- >>> Import Commands
- >>> commands.getstatusoutput (' ls-lt ') # return (status, output)
- (0, ' total 5900\n-rwxr-xr-x 1 long long ' 5 21:34 hello.sh\n-rw-r--r--1 long Long 147 Jan 5 21:34 makefile\n-rw-r--r--1 Long 6030829 Jan 5 21:34 log ')
- >>> commands.getoutput (' ls-lt ') # Returns the output of the command (seemingly different from the output format of the shell command)
- ' Total 5900\n-rwxr-xr-x 1 long Long 5 21:34 hello.sh\n-rw-r--r--1 Long Long 147 Jan 5 21:34 makefile\n- rw-r--r--1 Long 6030829 Jan 5 21:34 log '
- >>> commands.getstatus (' log ') # Call the command in Commands.getoutput to do the same for the ' log ' file
- '-rw-r--r--1 long long 6030829 Jan 5 21:34 log '
- >>>
3. subprocess Module
According to the official Python documentation, the subprocess module is used to replace the above modules. There is a python-implemented parallel SSH tool-MSSH, the code is very short, but it is interesting, it calls subprocess in the thread to start the child process to work.
[Python]View Plaincopy
- >>> from subprocess import call
- >>> Call (["ls", "-l"])
The advantage of subprocess compared to the system is that it is more flexible (you can get standard output, standard error, "Real" status code, better error handling, etc...) )。 I think the use of os.system is outdated, or is about to become obsolete.
4. Comparison and summary of the public methods4.1. About Os.system
Os.system ("Some_command with args") passes commands and parameters to your system shell, which is good because you can run multiple commands at the same time in this way and you can set up pipelines and input and output redirects. Like what:
Os.system ("Some_command < Input_file | Another_command > Output_file ")
However, while this is convenient, you need to handle the escape of shell characters manually, such as spaces. In addition, this will only allow you to run simple shell commands and not run external programs.
4.2. About Os.popen
Using stream = Os.popen ("Some_command with args") can do the same thing as Os.system, and unlike Os.system, Os.popen returns a class file object that uses it to access the standard input and output.
4.3. About Subprocess.popen
subprocess module, intended as an alternative to Os.popen, but because For example, you can use print Popen ("Echo Hello World", Stdout=pipe, Shell=true). Stdout.read () to replace print Os.popen ("Echo Hello World"). Read (). However, it is good to use a unified class that includes 4 different popen functions.
/span>
4.4. About subprocess.call
subprocess module. return_code = subprocess.call ("Echo Hello World ", Shell=true)
The OS module also has the Fork/exec/spawn function in C, but I don't recommend using them directly. subprocess may be more suitable for you.
===========================================
[2] http ://m.blog.csdn.net/blog/overstack/9295995
The following is an official Python document for the content covered in this article:
[4] Http://docs.python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module-- about using subprocess to replace old methods
[5] http://docs.python.org/lib/os-process.html--the Exec method family of the OS and the System method
[6] http://docs.python.org/lib/os-newstreams.html--Popen method of OS
[7] http://docs.python.org/lib/node528.html--subprocess Introduction to the OS
Python calls the Linux shell