subprocess batch execution of Linux commands in Python

Source: Internet
Author: User
This article gives you a detailed account of Python in the use of subprocess batch execution of Linux commands, interested Friends reference learning.

The relevant modules and functions that can execute shell commands are:

    • Os.system

    • Os.spawn

    • Os.popen--Waste

    • Popen--Waste

    • Commands-Discarded, removed in 3.x

The functions of the relevant modules and functions for executing shell commands are implemented in the Subprocess module and provide richer functionality.

Subprocess

Pager

Execute command, return status code

>>> import subprocess>>> ret = Subprocess.call (["LS", "-l"], Shell=false) Total 4684-rw-r--r--1 root ro OT   454 5 12:20 aa.py-rw-r--r--1 root root    0 May 8 16:51 aa.txt-rw-r--r--1 root root 4783286 Apr one 16:39 Doc kertoolbox.exe-rw-r--r--1 root root   422 May 5 12:20 ip_info.txt-rw-r--r--1 root root   718 Apr 10:52 my.cnf> >> ret = Subprocess.call ("Ls-l", Shell=true) Total 4684-rw-r--r--1 root root   454 5 12:20 aa.py-rw-r--r--1 Root root    0 May 8 16:51 aa.txt-rw-r--r--1 root root 4783286 Apr 16:39 dockertoolbox.exe-rw-r--r--1 root root   422 May 5 12:20 ip_info.txt-rw-r--r--1 root root   718 Apr 10:52 my.cnf>>> print (ret) 0

Check_call

Executes the command, returns 0 if the execution status code is 0, or throws an exception

>>> subprocess.check_call (["LS", "-l"]) total 4684-rw-r--r--1 root root   454 May 5 12:20 aa.py-rw-r--r--1 roo  T root    0 May 8 16:51 aa.txt-rw-r--r--1 root root 4783286 Apr 16:39 dockertoolbox.exe-rw-r--r--1 root root   422 May 5 12:20 ip_info.txt-rw-r--r--1 root root   718 Apr 10:52 my.cnf0>>> subprocess.check_call ("Exit 1", SH Ell=true) Traceback (most recent): File ' <stdin> ', line 1, <module> file '/usr/local/python3.5/lib /python3.5/subprocess.py ", line 581, in Check_call  raise Calledprocesserror (Retcode, cmd) subprocess. Calledprocesserror:command ' exit 1 ' returned Non-zero exit status 1

Check_output

Executes the command, if the status code is 0, returns the execution result, otherwise throws an exception

>>> subprocess.check_output (["echo", "Hello world!"]) B ' Hello world!\n ' >>> subprocess.check_output ("Exit 1", Shell=true) Traceback (most recent call last): File "< Stdin> ", line 1, in <module> File"/usr/local/python3.5/lib/python3.5/subprocess.py ", line 626, in Check_output  **kwargs). StdOut File "/usr/local/python3.5/lib/python3.5/subprocess.py", line 708, in run  output=stdout, Stderr=stderr) subprocess. Calledprocesserror:command ' exit 1 ' returned Non-zero exit status 1

Subprocess. Popen (...)

Used to perform complex system commands

Parameters:

The Args:shell command, which can be a string or sequence type (for example: list, tuple)

BufSize: Specifies buffering. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering

stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively

PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run

CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.

Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.

Shell: Ibid.

CWD: Used to set the current directory of child processes

ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.

Universal_newlines: Different system newline characters, True----agree to use N

Startupinfo and Createionflags are only valid under Windows

will be passed to the underlying CreateProcess () function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc.

Execute common commands

>>> import subprocess>>> Ret1 = subprocess. Popen (["mkdir", "T1"]) >>> Ret2 = subprocess. Popen ("mkdir T2", shell=true) >>> print (RET1) <subprocess. Popen object at 0x7f4d7609dd30>>>> print (Ret2) <subprocess. Popen Object at 0x7f4d7609dc18>

The commands for terminal input are divided into two types:

    • Input can be output, such as: ifconfig

    • Input to an environment that relies on re-entry, such as: Python

>>> import subprocess>>> obj = subprocess. Popen ("mkdir T3", Shell=true, cwd= '/tmp/',) >>> import subprocess>>> obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, Universal_newlines=true) >>> obj.stdin.write ("print (1) \ n") 9>>> Obj.stdin.write ("Print (2)") 8>>> obj.stdin.close () >>> cmd_out = Obj.stdout.read () >>> obj.stdout.close () >>> Cmd_error = Obj.stderr.read () >>> obj.stderr.close () >>> print (cmd_out) 12>>> print (cmd_ Error

>>> import subprocess>>> >>> obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, Universal_newlines=true) >>> obj.stdin.write ("print (1) \ n") 9>>> Obj.stdin.write ("Print (2)") 8>>> >>> out_error_list = obj.communicate () >>> print (out_error_list) (' 1\n2\n ', ')

>>> obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE, universal_newlines=true) >>> out_error_list = Obj.communicate (' Print ("' Hello ') ') >>> print (out _error_list) (' hello\n ', ')

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.