Python3 executes system commands and obtains real time echo function
- 2021-07-13 05:30:09
- OfStack
Let's introduce Python3 to execute system commands and get real-time echo
Recently, some packaged logic was reformed, which was originally made based on batch processing under Windows. Because batch processing is not very convenient to use, some real-time calculations are basically incompetent, so we turned to Python3. However, on the basis of previous scripts, many system commands need to be called, such as VS compiling a project, and we need to get real-time echo to know the compilation results and progress. So there are the following methods:
@staticmethod
def __external_cmd(cmd, code="utf8"):
print(cmd)
process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while process.poll() is None:
line = process.stdout.readline()
line = line.strip()
if line:
print(line.decode(code, 'ignore'))
Called directly when in use
__external_cmd
Method, pass in the system command you want to execute, and set the following code according to the echo content. This is more convenient to use.
ps: Let's look at several ways Python executes system commands and gets output
Method 1:
import os
p = os.popen('uptime')
x=p.read()
print x
Method 2:
import subprocess
res = subprocess.Popen('uptime',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
result = res.stdout.readlines()
Summarize