Using Python and external programs
Question: By using python, how do I use cmd.exe supported commands and get the output to
be viewed back in python? The reason I am doing this is to get the Microsoft
.NET framework version. At the moment I could only find it through the cmd.exe
by using the following command:

    
    
    wmic product where "Name like 'Microsoft .Net%'" get Name, Version
    

So I was thinking to get python to execute the above command and get the
results back and write them to a file.


Answer: Here is a way about how to execute cmd command from python using the
[subprocess](https://docs.python.org/2/library/subprocess.html#module-
subprocess) module.

**Code** : The following code is just pinging the loopback address using `ping
127.0.0.1` command and then writing the results to a file.
[Docs](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-
writing-files) for file handling in python could be found
[here](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-
writing-files).

    
    
    import subprocess
    
    def myFunc():   
        p = subprocess.Popen("ping 127.0.0.1", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        print out
        print err
        with open('myOutputFile.txt', 'w') as f:
            f.write(out) #Write the output to a file
    myFunc()
    

Replace the `ping 127.0.0.1` with other cmd command and it should work. For
eg: `netstat -a`.

Note: It might take a while before you see the output in console, because the
output will be returned to the console when the cmd command has finished the
execution!

The following code should do your job:

    
    
    import subprocess
    
    def myFunc():   
        p = subprocess.Popen("wmic product where \"Name like 'Microsoft .Net%'\" get Name, Version", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        print out
        print err
        with open('myOutputFile.txt', 'w') as f:
            f.write(out) #Write the output to a file
    myFunc()
    

Hope it helps!

