1. Simple code
It is relatively simple to understand directly. Os is simple and has relatively little control power. Subprocess can obtain the corresponding cmd output, which is convenient for further analysis of the running results.
#import os #("c:\\") import subprocess cmd = ' c:\\' p = (" /c" + "c:\\ abc", stdout=, stderr=) curline = () while(curline != b''): print(curline) curline = () () print()
Attached documents:
echo Hello world! echo show %1%
After running, the following results are output:
b'\r\n'
b'c:\\Python34>echo Hello world! \r\n'
b'Hello world!\r\n'
b'\r\n'
b'c:\\Python34>echo show abc \r\n'
b'show abc\r\n'
0
2. A little more complicated code
For ordinary applications, the above code is enough. If the batch file is special, for example, the started batch process has keyboard input parameters, then the above code will have problems, such as the batch file below:
@echo off echo Show command line parameters %1% set /p ver=Please enter a version: echo The entered version is:%ver%
This file contains two parameter inputs:
- One is the command line parameters
- The second is keyboard input parameters
The user is required to enter the version number during execution. If the previous code is used,
You will find that the program always does not enter a prompt, and when you enter it, the prompts and results will come out together.
The reason is that the readline() data is marked with a carriage return.
The prompt statement does not prompt for a line break, so the prompt text cannot be read until the operation is completed.
Understand the reason:
The improved method is also released. Only a single character is read and displayed until it cannot be read. Functions like print are broken by default and output immediately. Parameters must be added to print in file format. In addition, the previous data conversion is a one-time conversion, and there will generally be no exceptions. For single byte reading, the conversion will have exceptions for Chinese characters, and must be processed specifically.
The following is the modified code:
import subprocess cmd = ' c:\\' p = (" /c" + "c:\\ abc", stdout=, stderr=) byte_data = (1) word_data = b'' while(byte_data != b''): word_data += byte_data try: showdata = word_data.decode('gb2312') print(showdata, end="", flush=True) word_data = b'' except Exception as e: #print(e) a=0 byte_data = (1) () print()
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.