I have the following git extension script:
#!/usr/bin/env python
import sys
from subprocess import Popen, PIPE
if len(sys.argv) <= 1:
sys.argv = sys.argv + ['status']
git_cmd = 'git ' + ' '.join(sys.argv[1:])
print('--->', git_cmd)
#p = Popen(['git'] + sys.argv[1:], shell=True, stdout=PIPE)
p = Popen(git_cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
print(out)
#print(str(out).encode('ascii'))
#print(out.decode('ascii'))
Basically I want to get the output of my Git command in a variable but I also want it to preserve the terminal color codes in the variable. So when I call print(out), it should print the colors too. Currently the string given back to me after calling communicate() does not have color information. If I remove stdout=PIPE from Popen(), then I do get colors, but the output goes directly to the output and I do not get it in a variable.
I'm running Python 3.4 rc2 on Windows through msysgit (not cmd.exe). So for example I will do this:
git index status --short
The command it runs is git status --short, the output contains no color information, but when I run the same command directly in msysgit terminal, it gives me colors.
Anyone know how I can get the color information back?
git_cmdstring (which impliesshell=True) is bad form. Pass in an explicit argument array, and don't setshell=True, if you want better-defined behavior (where you don't run the risk ofcmd.exeparsing your command line incorrectly).