Home  >  Article  >  Backend Development  >  How to write python inspection script

How to write python inspection script

PHPz
PHPzforward
2023-05-10 13:22:061570browse

Method 1, use the system method of the os module

os.system (cmd), the return value is the status code returned after the shell command is run,
int type,
0-- Indicates that the shell command was executed successfully,
256-- indicates that the shell was not found,
This method is suitable for scenarios where the shell command does not need to output content.

How to write python inspection script

Method 2, use os.popen()

This method returns the result of running the shell command in the form of a file,
needs to obtain the content You can use the read() or readlines() method, for example:

How to write python inspection script

How to write python inspection script

##Method 3. Using the commands module, there are three methods. Use

(1) commands.getstatusoutput(cmd), which returns the output result and status code in the form of a string, that is, (status, output).

(2) commands.getoutput(cmd), returns the output result of cmd.

(3) commands.getstatus(file), returns the execution result string of ls -l file, calls getoutput, this method is not recommended

How to write python inspection script

How to write python inspection script

Method 4, subprocess module

allows the creation of many subprocesses. When creating, you can specify the subprocess and the input, output, and error output pipes of the subprocess, and you can obtain the output after execution. results and execution status.

(1) subprocess.run(): A new function in python3.5, executes the specified command, waits for the command to be executed, and returns an instance of the CompletedProcess class containing the execution result.

(2) subprocess.call(): Execute the specified command and return the command execution status. The function is similar to os.system (cmd).

(3) subprocess.check_call(): A new function in python2.5, which executes the specified command and returns a status code if the execution is successful, otherwise an exception is thrown.

Description: subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)

  subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

args: represents the shell instruction. If the shell instruction is given in string form, such as "ls -l", you need to make shell = Ture . Otherwise, shell variables are expressed in array form by default, such as "ls", "-l".

When using more complex shell statements, you can first use the shlex.split() method of the shlex module to help format the command, and then pass it to the run() method or Popen.

How to write python inspection script

How to write python inspection script

Attached is the source code of the subprocess module in python2.7 for understanding (pycharm to view the method source code, ctrl left click).

# Stubs for subprocess

# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub

from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text

_FILE = Union[None, int, IO[Any]]
_TXT = Union[bytes, Text]
_CMD = Union[_TXT, Sequence[_TXT]]
_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]

# Same args as Popen.__init__
def call(args: _CMD,
         bufsize: int = ...,
         executable: _TXT = ...,
         stdin: _FILE = ...,
         stdout: _FILE = ...,
         stderr: _FILE = ...,
         preexec_fn: Callable[[], Any] = ...,
         close_fds: bool = ...,
         shell: bool = ...,
         cwd: _TXT = ...,
         env: _ENV = ...,
         universal_newlines: bool = ...,
         startupinfo: Any = ...,
         creationflags: int = ...) -> int: ...

def check_call(args: _CMD,
               bufsize: int = ...,
               executable: _TXT = ...,
               stdin: _FILE = ...,
               stdout: _FILE = ...,
               stderr: _FILE = ...,
               preexec_fn: Callable[[], Any] = ...,
               close_fds: bool = ...,
               shell: bool = ...,
               cwd: _TXT = ...,
               env: _ENV = ...,
               universal_newlines: bool = ...,
               startupinfo: Any = ...,
               creationflags: int = ...) -> int: ...

# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
                 bufsize: int = ...,
                 executable: _TXT = ...,
                 stdin: _FILE = ...,
                 stderr: _FILE = ...,
                 preexec_fn: Callable[[], Any] = ...,
                 close_fds: bool = ...,
                 shell: bool = ...,
                 cwd: _TXT = ...,
                 env: _ENV = ...,
                 universal_newlines: bool = ...,
                 startupinfo: Any = ...,
                 creationflags: int = ...) -> bytes: ...

PIPE = ...  # type: int
STDOUT = ...  # type: int

class CalledProcessError(Exception):
    returncode = 0
    # morally: _CMD
    cmd = ...  # type: Any
    # morally: Optional[bytes]
    output = ...  # type: Any

    def __init__(self,
                 returncode: int,
                 cmd: _CMD,
                 output: Optional[bytes] = ...) -> None: ...

class Popen:
    stdin = ...  # type: Optional[IO[Any]]
    stdout = ...  # type: Optional[IO[Any]]
    stderr = ...  # type: Optional[IO[Any]]
    pid = 0
    returncode = 0

    def __init__(self,
                 args: _CMD,
                 bufsize: int = ...,
                 executable: Optional[_TXT] = ...,
                 stdin: Optional[_FILE] = ...,
                 stdout: Optional[_FILE] = ...,
                 stderr: Optional[_FILE] = ...,
                 preexec_fn: Optional[Callable[[], Any]] = ...,
                 close_fds: bool = ...,
                 shell: bool = ...,
                 cwd: Optional[_TXT] = ...,
                 env: Optional[_ENV] = ...,
                 universal_newlines: bool = ...,
                 startupinfo: Optional[Any] = ...,
                 creationflags: int = ...) -> None: ...

    def poll(self) -> int: ...
    def wait(self) -> int: ...
    # morally: -> Tuple[Optional[bytes], Optional[bytes]]
    def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ...
    def send_signal(self, signal: int) -> None: ...
    def terminate(self) -> None: ...
    def kill(self) -> None: ...
    def __enter__(self) -> 'Popen': ...
    def __exit__(self, type, value, traceback) -> bool: ...

# Windows-only: STARTUPINFO etc.

STD_INPUT_HANDLE = ...  # type: Any
STD_OUTPUT_HANDLE = ...  # type: Any
STD_ERROR_HANDLE = ...  # type: Any
SW_HIDE = ...  # type: Any
STARTF_USESTDHANDLES = ...  # type: Any
STARTF_USESHOWWINDOW = ...  # type: Any
CREATE_NEW_CONSOLE = ...  # type: Any
CREATE_NEW_PROCESS_GROUP = ...  # type: Any

The above is the detailed content of How to write python inspection script. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete