[Python Basics] Four ways to execute system commands in python code

1. The os.system method

返回信息Run the system command in the sub-terminal, you can get the and after the command is executed 执行返回的状态.
After execution, two lines of results are returned:

  • The first row is the result,
  • The second line is the execution status information. If the command is successfully executed, this statement returns 0, otherwise it returns 1.
import os

print(os.system('date'))

insert image description here
Because python3 uses UTF-8encoding by default, and the CMD window of WIN8 uses GBKencoding, resulting in different encodings.

However, simple encode('gbk')methods such as passing cannot solve the fundamental problem.

Especially when we do not use the print command to output at all 控制台默认输出, there is no way to modify the encoding format of os.system, because what os.system executes the command returns is not the text that appears in the command, but an int , when it is 0, it means success, and when it is 1, it means exception.

The solution under Pycharm:
insert image description here
insert image description here

Two, os.popen method

The os.popen() method not only executes the command but also returns the executed information object (commonly used 需要获取执行命令后的返回信息), and returns the result through a pipeline file.

import os
os.popen()

insert image description here
Use os.popen('指令').read()to back and forth to return specific information.
insert image description here

Three, common module

insert image description here
Note 1: It is used under the class unixsystem 此方法返回的返回值(status)与 脚本或命令执行之后的返回值不等. This is because os.wait() is called. For the specific reason, you have to understand the implementation of the system wait(). Need the correct return value (status), just need 对返回值进行右移8位操作it.

Note 2: When the parameter or return of the command is included 中文文字, it is recommended to use it subprocess.

Four, subprocess module

The subprocess module uses the control and monitoring of the thread, assigns the returned result to a variable, and facilitates the processing of the program.

The subprocess module is a module introduced by python since version 2.4. It is mainly used to replace some old module methods, such as os.system, os.spawn*, os.popen*, commands.*, etc.

The subprocess passes 子进程through 执行外部指令, and passes through input/output/error管道, to obtain the return information of the execution of the subprocess.
insert image description here
For the usage of specific subprocess, see this blog for details

Guess you like

Origin blog.csdn.net/All_In_gzx_cc/article/details/127731343