How to execute a VS2008 command from Python and grab its output?
-
20-09-2019 - |
Question
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:
- Run the process from a particular directory (preferably without using chdir)
- Executing a command which contains environment variables + custom text.
- 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()
OTHER TIPS
Have a look at this code I used here to do the job that you're looking for. This is written in C#, and is a flexible class, you just need to change the command, look in ps.FileName
and ps.Arguments
, the output of the command gets redirected to a StringBuilder
instance for parsing if so required. The shell executing command in a window is completely hidden and does not show.
Hope this helps, Best regards, Tom.