Python cut Linux shell command

Source: Internet
Author: User
Tags echo command
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 15:14 log —————— > 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 21:00 hello.sh

-rw-r--r--1 Long 147 Jan 5 20:26 Makefile

Drwxr-xr-x 3 long 4096 Jan 2 19:37 test

-rw-r--r--1 root root 6030829 Dec 15:14 log

Drwxr-xr-x 2 long 4096 Dec 09:36 Pip_build_long

DRWX------2 DEBIAN-GDM debian-gdm 4096 Dec 19:08 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

long@zhouyl:/tmp/tests$ python

Python 2.7.3 (Default, Jan 2 2013, 16:53:07)

[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 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 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 methods

4.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

The Popen class of the subprocess module is intended as an alternative to Os.popen, but is slightly more complex than os.popen because it is comprehensive.
For example, you can use print Popen ("Echo Hello World", Stdout=pipe, Shell=true). Stdout.read () to replace print os.popen ("Echo Hello World"). Rea D (). However, it is good to use a unified class that includes 4 different popen functions.

4.4. About Subprocess.call

The call function of the subprocess module. It is basically like the Popen class and uses the same parameters, but it simply waits for the command to complete and gives you a return code. Like what:
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.


===========================================
[1] http://demi-panda.com/2013/01/25/python-shell-command/index.html
[2] http://m.blog.csdn.net/blog/overstack/9295995
[3] http://blog.csdn.net/swiftshow/article/details/7755543

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

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.