SoFunction
Updated on 2024-11-16

Python call bash shell script method

1. ()

help()

1.1. demo

  • (command):This method returns a 16-bit binary number after calling the shell script, the
  • The low bit is the signal number that kills the called script, and the high bit is the exit status code of the script that
  • That is, after the execution of the exit 1 code in the script, theThe high digit of the function's return value is then 1, and if the low digit is 0 in the case of the
  • The return value of the function is 0x0100, which is converted to decimal to get 256.
  • to obtainthe correct return value, the return value can be restored using a bit shift operation (shifting the return value 8 bits to the right):
>>> import os
>>> ("./")
hello python!
hello world!
256
>>> n>>8
1

2. ()

help()

2.1 demo

(command):This call is piped in such a way that the function returns a file object, the
The content inside is the output of the script (which can be simply interpreted as the echo output), using thecall (programming)present situation

>> import os
>>> ("./")
<open file './', mode 'r' at 0x7f6cbbbee4b0>
>>> f=("./")
>>> f
<open file './', mode 'r' at 0x7f6cbbbee540>
>>> ()
['hello python!\n', 'hello world!\n']

3. Commands module

  • (1) (cmd), which returns the output result and status code as a string, i.e. (status,output).
  • (2)(cmd), returns the output of cmd.
  • (3)(file), which returns the result string of the execution of ls -l file, invokes thegetoutputThis method is not recommended

4. subprocess

subprocessmodule, allowing the creation of many sub-processes, the creation of sub-processes and sub-processes can be specified at the time of input, output, error output pipeline, after the execution of the output can be obtained and the status of the execution.

  • (1) (): a new function in python 3.5, executes the specified command, waits for the completion of the command to return an instance of the CompletedProcess class containing the result of the execution.
  • (2) (): Execute the specified command, return to the command execution status, function similar to (cmd).
  • (3) subprocess.check_call(): a new function in python2.5, executes the specified command, returns a status code if the execution succeeds, otherwise throws an exception.

Description:(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
(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: Indicates shell commands, if the shell command is given as a string, e.g. "ls -l", then you need to make shell = Ture, otherwise the default is an array of shell variables, e.g. "ls","-l".
When using more complex shell statements, you can use the shlex module's () method to help format the command before passing it to therun()Methods orPopen

4.1 demo

Stubs for subprocess

Based on /2/library/ 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

to this article on the python call bash shell script method is introduced to this article, more related python call bash shell script content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!