Python calls Linux system commands--using the subprocess module

Source: Internet
Author: User

Call the system command in Python if you are using subprocess. The Popen () module, in the form of command parameters, can be divided into two types:

    1. Pass the command as a string to subprocess. Popen ()

    2. Save the command to a tuple, list sequence, and then pass it to subprocess. Popen ()



The subprocess module uses the Popen class to create a child Process execution command, first subprocess. Prototype of Popen ():


Subprocess. Popen (args, bufsize=0, Executable=none, Stdin=none, Stdout=none, Stderr=none, Preexec_fn=none, Close_fds=false, shell= False, Cwd=none, Env=none, Universal_newlines=false, Startupinfo=none, creationflags=0)


Parameter description:

Args: Commands executed by Python are typically passed in as strings, or as sequences (tuples or lists). If args is a tuple or list form, the first element of the sequence is the executable file of the command. You can also use executable to explicitly specify the path to the executable file.


stdin, stdout, stderr: Used for communication with the outside. You can use subprcess. The PIPE is initialized. When stdin, stdout, stderr are initialized, they can communicate with the outside for complex communication.

Such as:

p = subprocess. Popen () creates a child process p execution command, external to the command to pass parameters, you can use the P.communicate (Stdin_some) method, Stdin_some incoming P.stdin standard input.

At the same time p.commucincate () returns a tuple value (stdout_some, stderr_some) = P.communicate (stdin_some). So, call subprocess. Popen () Creates a child Process execution command, which makes it easy to communicate with the child process and get the state.

Note: If you need to use the communication () method to communicate with a child process, stdin, stdout, stderr, are required to use subprocess when creating the subprocess. PIPE initialization.


Shell: The default is False, if the form of args is a string, then shell=true, the specified command is executed with the shell. If the form of args is a tuple or list, then shell=false specifies that the command does not need to be executed in the shell.


ENV: A dictionary that specifies the run environment for a child process, the default is None, which indicates that the child process inherits the environment variables of the parent process.


Subprocess. Some methods of Popen:


popen.communicate (): With external communication, (out, errout) = Popen.communicate (), return standard output and error output.


Popen.poll (): Checks the status of the child process, if none is running, exits if it is 0, and exits unexpectedly if it is-N.


Popen.wait (): Wait for the process to end and get the return code.


Popen.pid: Returns the process PID number


Popen.kill (): Kill process


Example:

1. Pass in as a string, Shell=true:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/88/FC/wKiom1gDp4-ChGwVAACOO7GVpf4559.png "title=" Popen_ Str "alt=" Wkiom1gdp4-chgwvaacoo7gvpf4559.png "/>

In [127] Line: Create Popen object, Popen execute ' ls-l. ' command in child process, list file of current directory, command execution result in standard output stdout, because stdout is initialized with pipe,

So, in the [129] line, the contents are read out with P.stdout.read ().


2. Pass in the command in a sequential manner, Shell=false:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/88/F9/wKioL1gDqx_DabJPAABth-iAZ-0589.png "title=" Popen_ List "alt=" Wkiol1gdqx_dabjpaabth-iaz-0589.png "/>

Save the command in the form of a sequence, you do not need to specify shell=true to run the instruction. The operation result of the instruction is also saved in stdout, and the result is read out by the ReadLines () method.


3. Use the Communicate () method to communicate with the instruction:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/88/FC/wKiom1gDrWSxyNoIAAB_CAmyNKs317.png "title=" Popen_ Communicate.png "alt=" Wkiom1gdrwsxynoiaab_camynks317.png "/>

Another parameter path name for the ' ls-l ' command, passed in through Communicat ('/tmp '), results in a tuple (OUTSTD, Outerr) receive.


4. More than one command is connected:

Under Linux, it is common to use pipelines to connect multiple commands together, and the result of the previous instruction is the input of the latter instruction, which can be implemented using Popen.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/88/F9/wKioL1gDr-fCPW7eAABBeaslrTM068.png "title=" Pipe.png "alt=" Wkiol1gdr-fcpw7eaabbeaslrtm068.png "/>

First, view the contents of the Test.txt file.

Then, the sub-process PB standard input stdin is initialized with Pa.stdout, realizes the function of the pipeline, the output of PA process programmed the input of PB process, the final output result.


This article is from the "dayandnight" blog, make sure to keep this source http://hellocjq.blog.51cto.com/11336969/1862497

Python calls Linux system commands--using the subprocess module

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.