Search code examples
pythonvisual-studio-2008shellexecute

How to execute a VS2008 command from Python and grab its output?


I wish to run

tf changeset 12345

Using the Visual Studio 2008 Command tool. It is located in: "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\" and the command that gets launched is: %comspec% /k ""c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86

I would like to append the "tf changeset 12345" to it somehow and save it to a string WITHOUT first redirecting it to a file. I noticed that when I simply call it from the command line, I get GUI when I type:

tf changeset 12345

and I get the textual output when I do:

tf changeset 12345 > out.txt

I prefer not to create a file on the file system, but hopefully just read it in the "Pythonic way".

I have seen brief examples of os.system(), subprocess, but none of them seem to illustrate how to do what I want to do:

  1. Run the process from a particular directory (preferably without using chdir)
  2. Executing a command which contains environment variables + custom text.
  3. Redirect the output without creating a temporary file.

Hopefully you can help me get close to what I want. It would help if you tested the solution on VS2008 or some other Windows program.

Thank you!


Solution

  • process = subprocess.Popen(['tf', 'changeset', '12345'], cwd='c:/somedir', env={'SOMEENVVAR': 'SOMEVALUE', ...}, stdout=subprocess.PIPE)
    
    for line in process.stdout:
      print line
    
    process.terminate()