"Python standard library"--subprocess < run external commands >

Source: Internet
Author: User

Role: Create additional processes and communicate with them. This is especially helpful if a program needs to produce or take advantage of text, because the API supports passing data back and forth through the standard input and output channels of the new process.

The Subprocess module provides a consistent way to create and process additional processes. Compared to other modules in the standard library, it provides a more advanced interface to replace the Popen () functions in the Os.system (), OS.SPAWNV (), OS, and Popen2 modules, as well as commands ().

The Subprocess module defines a class Popen and also defines some wrapper functions that use this class. The Popen constructor establishes a new process based on some parameters so that the parent process can communicate with it through the pipeline. Compared to other modules and functions it replaces, subprocess can provide all its functions, or even more. In all cases, this API usage is consistent, and many additional steps that require overhead, such as closing additional file descriptors and ensuring that pipelines are closed, are "built-in" without the need for application code to handle them separately.

You can use the call () function to run an external command, but not to interact with it in the same way as Os.system (). Command-line arguments are passed in as a list of strings, so there is no need to escape quotes or other special characters that might be interpreted by the shell.

1 Import subprocess 2 >>> subprocess.call (['ls','-l'])  3data4test.py506 >> >

Setting the shell parameter to a value of true causes Subprocess to create an intermediate shell process that runs the command from this process. The command is run directly by default.

Import subprocess>>> subprocess.call ('ls-l', shell=drwxr -xr-x 2 root root 4096 August   9 22:29 data-rw-r--r--1 root root  469 August   7 22:52 test.py0 >>>

The return value of call () is the program's exit code. The caller is responsible for interpreting the return value to detect the error. The Check_call () function works like call () except that checking the exit code results in an CALLEDPROCESSSERROR exception if an error is indicated.

1>>>Importsubprocess2>>>Try:3... Subprocess.check_call (['false'])4...exceptsubprocess. Calledprocesserror as err:5...Print 'ERROR:', Err6 ... 7Error:command'['False']'Returned Non-zero exit status 18>>>

For the process initiated by call (), its standard input and output channels are bound to the input and output of the parent process. This means that the caller cannot capture the output of the command. You can use Check_output () to capture the output for later processing. The Ls-l command runs successfully, so it prints to standard output to text that is captured and returned.

1>>>Importsubprocess2>>> output = Subprocess.check_output (['ls','- L'])3>>>Print 'Has %d bytes in output'%len (Output)4Have 822 bytesinchOutput5>>>PrintOutput6Total Dosage 567Drwxr-xr-x 2 root root 4096 August 9 22:29Data8-rw-r--r--1 root root 469 August 7 22:52test.py9 Ten>>>

The next example runs a series of commands in a child shell. The message is sent to standard output and standard error output before the command returns an error code and exits. Messages sent to the standard error output are printed to the console, but messages sent to standard output are hidden.

1>>>Importsubprocess2>>>Try:3... Output =Subprocess.check_output (4...'Echo to stdout, Echo to stderr 1>&2; exit 1',5... shell=True,
#stderr =subprocess. STDOUT 6 ... )7...exceptsubprocess. Calledprocesserror as err:8...Print 'ERROR:', Err9...Else:Ten...Print 'Has %d bytes in output'%len (Output) One...PrintOutput A ... - This sentence is not output when the stderr parameter in the to StdErr #将check_output () is set to constant stdout. -Error:command'Echo to stdout, Echo to stderr 1>&2; exit 1'Returned Non-zero exit status 1 the>>>

"Python standard library"--subprocess < run external commands >

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.