Use Python to execute shell scripts and dynamically transmit and subprocess basic usage

Source: Internet
Author: User
Tags terminates
This article has shared the use of Python to execute shell scripts and dynamic communication and subprocess basic use, interested in small partners can take a look at

Recent job requirements have encountered this situation in the Web side to get the contents of the configuration file and into the shell script to dynamically pass in parameters

There are several ways to execute a shell script and finally choose Subprocess, the Python standard library

Subprocess This module can be very convenient to start a sub-process, and control its input and output

Class 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):
The parameters are:
Args should be a string, or a series of program parameters. The program to execute is usually the first item in the args sequence or string, but can be set explicitly using executable parameters.
On Unix, with Shell=false (default): In this case, the POPEN class uses OS.EXECVP () to execute the subroutine. Args should usually be a sequence. A string is treated as a string as a sequence of unique items (Programs to execute).

On UNIX, use Shell = True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies a command string, and any other items will be treated as additional shell parameters.

You can start by creating a simple shell script a.sh

$ $ to represent the first and second arguments that are passed into the script, respectively


If you do not write Shell=true, the default is Shell=false, you need to specify the actuator path in the first parameter of args



BufSize if given, the bufsize has the same meaning as the corresponding parameter of the built-in open () function: 0 for unbuffered, 1 for row buffering, and any other positive value means to use (approximately) a buffer of that size. Negative bufsize means using system defaults, which usually means full buffering. The default value for BufSize is 0 (no buffering).


Stdin,stdout and stderr Specify the standard input, standard output, and standard error file handles for the executed program, respectively. Valid values are pipe, existing file descriptor (positive integer), existing file object, and None. Pipe says a new pipe should be created for the child. With none, redirects do not occur; The child's file handle will inherit from the parent class. In addition, stderr can be stdout, which means that the STDERR data for the application should be captured in the same file handle as the stdout.

In the Popen object, you can set the value subprocess.stdout=pipe to remove the standard output of the process through the pipeline P.stdout.read ()


PREEXEC_FN If the PREEXEC_FN is set to a callable object, the object will be called before the child process executes.


If Close_fds is true, all file descriptors except 0,1 and 2 are closed before the child process is executed.


If the shell is true, the specified command is executed through the shell.


If CWD is not none, the current directory will be changed to CWD before the descendants are executed.


If Env is not none, it will define environment variables for the new process.


If you set Universal_newlines to True, file objects stdout and stderr will open as text files, but there may be a \ N,unix line-end Convention \ R,macintosh convention or any line in \ r \ n terminates, Windows contract. All these external representations are considered by the Python program as \ n. Note: This feature is only available when Python is built with Universal line-wrapping support (default). Additionally, the newlines properties of the file objects Stdout,stdin and stderr are not updated by the communications () method.


If Startupinfo and Creationflags are set, they are passed to the lower CreateProcess () function. They can specify such things as the appearance of the main window and the priority of the new procedure. (Windows only)


Some methods of Popen objects

Popen.poll () checks whether the child process terminates and returns the ReturnCode of the object

Popen.wait () Waits for the child process to complete, blocking. Back to ReturnCode

Popen.communicate (Input=none) inputs the information into the process, reading the data from stdout and stderr until the end of the file is reached. Wait for the process to terminate. The optional stdin parameter should be the string to send to the child process, or none if no data should be are sent to the child process.

Returns a tuple (STDOUT,STDERR) but the read data is cached in memory, so do not use this method if the amount of data is large or infinite

Popen.pid the PID of the returned child process

Popen.returncode The status code of the read process none--child process has not been completed;
==0--the child process to exit normally;
> 0--Sub-process abnormal exit, ReturnCode corresponding to the error code;

< 0--process was killed by the signal.

Popen.kill () Kill process

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.