Python executes commands via subprocess, redirects real-time output

Source: Internet
Author: User
Tags readline

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.