Environment: Python 3.6
The following example executes commands via subprocess, redirects and outputs in real time, which can be modified to redirect to a file or other.
(Note: the example only applies to commands that stop executing when an error is encountered.) )
One, to perform a ping command
ImportsubprocessImportSYS#Common CodingGBK ='GBK'UTF8='Utf-8'#decoding mode, general py file Execution for utf-8, cmd command for GBKCurrent_encoding =Gbkpopen= subprocess. Popen (['Ping','www.baidu.com'], stdout=subprocess. PIPE, stderr=subprocess. PIPE, BufSize=1)#REDIRECT standard output whilePopen.poll () = = None:#None indicates that the execution is in progressR =Popen.stdout.readline (). Decode (current_encoding) Sys.stdout.write (R)#can modify output mode, such as console, file, etc.#REDIRECT error outputifPopen.poll ()! = 0:#not 0 for error executionErr =Popen.stderr.read (). Decode (current_encoding) sys.stdout.write (err)#can modify output mode, such as console, file, etc.
Ii.. py File Implementation
ImportsubprocessImportSYS#Common CodingGBK ='GBK'UTF8='Utf-8'#decoding mode, general py file Execution for utf-8, cmd command for GBKCurrent_encoding =UTF8 Popen= subprocess. Popen (['python'+ U'D:\code\test.py"'], # The file path that needs to be executedstdout =subprocess. PIPE, stderr=subprocess. PIPE, BufSize=1)#REDIRECT standard output whilePopen.poll () = = None:#None indicates that the execution is in progressR =Popen.stdout.readline (). Decode (current_encoding) Sys.stdout.write (R)#can modify output mode, such as console, file, etc.#REDIRECT error outputifPopen.poll ()! = 0:#not 0 for error executionErr =Popen.stderr.read (). Decode (current_encoding) sys.stdout.write (err)#can modify output mode, such as console, file, etc.
Python executes commands via subprocess, redirects real-time output