Python Module-subprocess module

Source: Internet
Author: User
Tags string format

Run () method
>>> a = Subprocess.run ([' DF ', '-h ']) file system        capacity  used  available% mount point udev            468M     0  468M    0%/ Devtmpfs            98M  7.4M   91M    8%/run/dev/sda1        39G  5.0G   32G   14%/tmpfs           488M  216K  488M    1%/dev/shmtmpfs           5.0M  4.0K  5.0M    1%/run/locktmpfs           488M     0  488M    0%/sys/fs/cgrouptmpfs            98M   84K   98M    1%/run/user/1000>>> Acompletedprocess (args=[' df ', '-h '), returncode=0) >>> a.returncode  # Get Status code for command execution results 0>>> A.args  # Get command argument list [' DF ', '-h ']

Pass the command directly to the list

If you want to read the results and errors of the command execution, you need to pass the pipeline

>>> a = Subprocess.run ([' DF ', '-H '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> a.stdout # If the command executes successfully, you can read the execution result B ' \xe6\x96\x87\xe4\xbb\xb6\xe7\xb3\xbb\xe7\xbb\x9f \xe5\xae\xb9\xe9\x 87\x8f \xe5\xb7\xb2\xe7\x94\xa8 \xe5\x8f\xaf\xe7\x94\xa8 \xe5\xb7\xb2\xe7\x94\xa8% \xe6\x8c\x82\xe8\xbd\xbd\xe7\ X82\xb9\nudev 468M 0 468M 0%/dev\ntmpfs 98M 7.4M 91M 8%/run\n/dev/sda1 39G 5 .0G 32G 14%/\ntmpfs 488M 216K 488M 1%/dev/shm\ntmpfs 5.0M 4.0K 5.0M 1%/run/lock\ntmpf S 488M 0 488M 0%/sys/fs/cgroup\ntmpfs 98M 84K 98M 1%/run/user/1000\n ' >>> A.   Stdout.decode () ' File system capacity used available% mount point \nudev 468M 0 468M 0%/dev\ntmpfs 98M 7.4M           91M 8%/run\n/dev/sda1 39G 5.0G 32G 14%/\ntmpfs 488M 216K 488M 1%/DEV/SHM\NTMPFS  5.0M 4.0K 5.0M 1%/run/lock\ntmpfs 488M 0 488M  0%/sys/fs/cgroup\ntmpfs 98M 84K 98M 1%/run/user/1000\n ' >>> a.stderr # If the command executes successfully, the read error is empty B ' >>> a = Subprocess.run ([' DF ', '-ASDH '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> A.stdout.decode () # If the command executes an error, the read execution result is empty ' >>> a.stderr # If the command executes an error, you can read the wrong content B "df\xef\xbc\ X9A\XE6\X97\XA0\XE6\X95\X88\XE9\X80\X89\XE9\XA1\XB9--s\ntry ' df--help ' for more information.\n ' >>> A.stderr.decode () "DF: Invalid option--s\ntry ' df--help ' for more information.\n"

Stdout=subprocess. Pipe for the command to execute the contents of the successful return

Stderr=subprocess. Pipe error content returned for command execution error

Because the execution of a command will open a process, inter-process data can not communicate, so the operating system to read the results of stdout, stderr, and then passed to the program

Subprocess.run () method executes the command, if the command is wrong, the program will not error and continue to run, if the command is wrong when the program error stops running, you can add a check parameter

Checks if the command is wrong when the check parameter is set to True

>>> a = Subprocess.run ([' DF ', '-ASDH '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> A.stderr.decode () "DF: Invalid option--s\ntry ' df--help ' for more information.\n" >>> a = Subprocess.run ([' DF ', '-ASDH '],stdout=subprocess. Pipe,stderr=subprocess. Pipe,check=true) Traceback (most recent):  file ' <stdin> ', line 1, <module>  file '/usr/ lib/python3.5/subprocess.py ", line 708, in Run    output=stdout, Stderr=stderr) subprocess. Calledprocesserror:command ' [' DF ', '-ASDH '] ' returned Non-zero exit status 1

Execute a command with a pipe character

>>> a = Subprocess.run (' df-h |grep sda1 ', stdout=subprocess. Pipe,stderr=subprocess. Pipe,shell=true) >>> acompletedprocess (args= ' df-h |grep sda1 ', returncode=0, stdout=b '/dev/sda1        39G  5.0G   32G   14%/\n ', Stderr=b ')
Call () method

Executes the command, returning the command execution state

>>> retcode = Subprocess.call ([' DF ', '-h ']) file system        capacity  used  available% mount point udev            468M     0  468M    0%/devtmpfs            98M  7.4M   91M    8%/run/dev/sda1        39G  5.0G   32G   14%/TMPFS           488M  216K  488M    1%/dev/shmtmpfs           5.0M  4.0K  5.0M    1%/run/locktmpfs           488M     0  488M    0%/sys/fs/cgrouptmpfs            98M   84K   98M    1%/run/user/1000>>> Retcode0

Executes the command, if the command execution status is 0, returns normally, otherwise throws the exception

>>> Subprocess.check_call ([' DF ', '-h ']) file system        capacity  used  available% mount point udev            468M     0  468M    0%/devtmpfs            98M  7.4M   91M    8%/run/dev/sda1        39G  5.0G   32G   14%/tmpfs           488M  216K  488M    1%/dev/shmtmpfs           5.0M  4.0K  5.0M    1%/run/locktmpfs           488M     0  488M    0%/sys/fs/cgrouptmpfs            98M   84K   98M    1%/run/user/10000>>> Subprocess.check_call ([' DF ', '-ash ']) DF: Invalid option--stry ' df--help ' for more information. Traceback (most recent):  file ' <stdin> ', line 1, in <module>  file "/usr/lib/python3.5/ subprocess.py ", line 581, in Check_call    raise Calledprocesserror (Retcode, cmd) subprocess. Calledprocesserror:command ' [' DF ', '-ash '] ' returned Non-zero exit status 1

Receives a string format command, returns a tuple form, the 1th element is the execution state, and the 2nd is the command result

>>> subprocess.getstatusoutput (' WhoAmI ') (0, ' Sch01ar ')

Receives a string format command and returns the result

>>> subprocess.getoutput (' whoami ') ' Sch01ar '

Executes the command and returns the result

>>> subprocess.check_output ([' DF ', '-h ']). Decode () ' File system        capacity  used with  available% mount point \nudev            468M     0  468M    0%/dev\ntmpfs            98M  7.4M   91M    8%/run\n/dev/sda1        39G  5.0G   32G   14%/\ntmpfs           488M  216K  488M    1%/dev/shm\ntmpfs           5.0M  4.0K  5.0M    1%/run/ Lock\ntmpfs           488M     0  488M    0%/sys/fs/cgroup\ntmpfs            98M   84K   98M    1%/run/ User/1000\n ' >>> a = subprocess.check_output ([' DF ', '-h ']). Decode () >>> a ' file system        capacity  used  available% mount point \nudev            468M     0  468M    0%/dev\ntmpfs            98M  7.4M   91M    8%/run\n/ DEV/SDA1        39G  5.0G   32G   14%/\ntmpfs           488M  216K  488M    1%/DEV/SHM\NTMPFS           5.0M  4.0K  5.0M    1%/run/lock\ntmpfs           488M     0  488M    0%/SYS/FS/CGROUP\NTMPFS            98M   84K   98M    1%/run/user/1000\n '
Popen () method

The Popen () method executes the command's process and the main program's process is parallel

>>> Subprocess.run ([' Sleep ', ' ten '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) completedprocess (args=[' sleep ', ' ten '], returncode=0, stdout=b ', stderr=b ') >>> subprocess. Popen ([' Sleep ', '],stdout=subprocess '). Pipe,stderr=subprocess. PIPE) <subprocess. Popen Object at 0x7f7fe17adda0>

Subprocess.run () sleeps 10 seconds before returning, subprocess. Popen () return directly

>>> a = subprocess. Popen ([' Sleep ', '],stdout=subprocess '). Pipe,stderr=subprocess. PIPE) >>> a.wait () 0

Wait () waits for the process to end

>>> a = subprocess. Popen ([' WhoAmI '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> A.stdout.read ()  # Read command execution successful result B ' sch01ar\n ' >>> a.stderr.read ()  # Read command execution error result B ' >>> a.poll ()  #检查子进程是否已终止, return return value 0>>> A.args  # return command parameter [' WhoAmI ']>>> a.pid  # Returns the process number of the current command 24999>>> A.returncode  # Returns the return value 0

Terminate (): Signals the system, terminates the process that is started, does not necessarily terminate

Kill (): kills the process that was started

Communicate (): interacts with the initiating process, sends data to STDIN, and receives output from STDOUT, then waits for the task to end

>>> a = subprocess. Popen ([' Python3 ', ' test.py '],stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> a.communicate (' Sch01ar ') (b "a\x7fa.cco\t ' Ch01ar ') \ n", B ")

Communicate () can only interact with the initiated process once

Send_signal (): Send system signal

>>> a = subprocess. Popen ([' Sleep ', '],stdout=subprocess '). Pipe,stderr=subprocess. PIPE) >>> a.send_signal (signal. SIGKILL)

PREEXEC_FN: Valid only on UNIX platforms, specifying a function that will be called before the child process is run

>>> def test (): ...    Print (' This is a test ') ... >>> a = subprocess. Popen ([' WhoAmI '],stdout=subprocess. Pipe,stderr=subprocess. Pipe,preexec_fn=test) >>> a.stdout.read () b ' This is a test\nsch01ar\n '

CWD: Used to set the current directory of child processes

>>> a = subprocess. Popen (' Echo $PWD ', shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> a.stdout.read () b '/home/sch01ar\n ' >>> a = subprocess. Popen (' Echo $PWD ', shell=true,stdout=subprocess. Pipe,stderr=subprocess. Pipe,cwd= '/home/sch01ar/desktop/') >>> a.stdout.read () b '/home/sch01ar/desktop\n '

The shell acts like a shell in the Subprocess.run () method.

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

Python Module-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.