Detailed explanation of python os. system executing cmd instruction code

  • 2021-12-05 06:29:50
  • OfStack

1. Execute cmd instruction, and the output content in cmd will be directly output in the console, and the return result is 0, indicating successful execution.

2. After calling shell script, return a 16-bit binary number, the low order is the signal number to kill the called script, and the high order is the exit status code of the script.

The os. system () method simply executes the cmd instruction, and there is no way to get the output of cmd.

Instances


# coding:utf-8
import os
os.system("ls")

How does Python call cmd using the OS module

Two methods of calling cmd are provided in the os module, os. popen () and os. system ()

os. system (cmd) requires 1 terminal to be opened when executing command command, and the execution result of command command cannot be saved.

os. popen (cmd, mode) opens a pipeline to the command process. The return value is a file object that can be read or written (as determined by mode, the default is' r '). If mode is' r ', you can use the return value of this function to call read () to get the execution result of the command command.

os.system()

Definition:


def system(*args, **kwargs): # real signature unknown
  """ Execute the command in a subshell. """
  pass

Simply put, it is to execute the command command in shell

Example:


(venv) C:\Users\TynamYang>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import os
>>> cmd = 'echo "I am tynam"'
>>> os.system(cmd)
"I am tynam"
>>>

os.popen()

Definition:


# Supply os.popen()
def popen(cmd, mode="r", buffering=-1):
  if not isinstance(cmd, str):
    raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
  if mode not in ("r", "w"):
    raise ValueError("invalid mode %r" % mode)
  if buffering == 0 or buffering is None:
    raise ValueError("popen() does not support unbuffered streams")
  import subprocess, io
  if mode == "r":
    proc = subprocess.Popen(cmd,
                shell=True,
                stdout=subprocess.PIPE,
                bufsize=buffering)
    return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
  else:
    proc = subprocess.Popen(cmd,
                shell=True,
                stdin=subprocess.PIPE,
                bufsize=buffering)
    return _wrap_close(io.TextIOWrapper(proc.stdin), proc)

The command command is also executed in shell, but the result returned is a file object, which can be read and written

The meanings of three parameters are as follows:

command--shell commands executed

mode-Mode permissions, read ('r') or write ('w'), default to read ('r')

bufsize--No buffering occurs if the buffering value is set to 0. If the buffer value is 1, line buffering will be performed when the file is accessed. If the buffer value is set to an integer greater than 1, the buffer operation is performed at the set buffer size. If it is negative, the buffer size is the system default value (default behavior).

Example:


>>> import os
>>> cmd = 'echo "I am tynam"'
>>> f = os.popen(cmd, 'r')
>>> f.read()
'"I am tynam"\n'
>>>

Related articles: