Python--subprocess

Source: Internet
Author: User

Example 1: View the output of the Ipconfig-all command and save the output to the file Tmp.log:

= Open (R'd:\tmp.log','w') p=subprocess. Popen (['ipconfig','-all'], Stdout=handle)
If P.poll () ==none:
Print "end<<<<<<<<<<<<<<<<"
P.terminate ()
Handle.close ()

Example 2: View network Settings Ipconfig-all, save to variable:

#coding: utf-8= subprocess. Popen (['ipconfig','-all'], stdout=subprocess. pipe,shell=True) oc=output.communicate () #取出output中的字符串print oc[0] #打印网络信息

Example 3: Displaying the contents of a file t2.py

Import Subprocessy=subprocess.check_output (["type""t2.py "],shell=True" Print (y)

Example 4: Call the cmd command in the system to display the results of the command execution

Import SUBPROCESSX=subprocess.check_output (["echo"]  Hello world! "],shell=True" Print (x)

Example 5: Change standard input, standard output, and standard error when Popen () is established, and can take advantage of subprocess. Pipes connect the inputs and outputs of multiple sub-processes together to form a pipeline (pipe):

Import Subprocesschild1= subprocess. Popen (["dir","/w"], stdout=subprocess. Pipe,shell=True) child2= subprocess. Popen (["Echo","Hello"], stdin=child1.stdout,stdout=subprocess. Pipe,shell=True) out1=child1.communicate () out2=child2.communicate () print out2[0]print"********************" forIinchRange (len (OUT1)): Print Out1[i]

Example 6: If you want to communicate with a child thread frequently, you cannot use communicate (), because the communicate communication closes the pipeline once. You can try the following method:

import SUBPROCESSP=subprocess. Popen ("dir", Shell=true, stdout=subprocess. PIPE, stderr=subprocess. STDOUT)  while  True:      = p.stdout.readline ()      if" and P.poll ()! = None          :break

Python--subprocess

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.