0

Im trying to use some git commands in python through subprocess, currently I've got this command

git branch -r --merged | grep -v HEAD | xargs -L1 git --no-pager log --pretty=tformat:'%Cgreen%d%Creset %Cblue%ar%Creset' -1

which is giving me back this error b'fatal: malformed object name |\n'

I know why the error is there but im not entirely sure what I can replace the pipe in the git command with, any suggestions would be helpful and appreciated.

Tester code:

import subprocess

def cmd(command):
    p = subprocess.Popen(command.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    out, err = p.communicate()
    return out.decode("utf-8"), err

def test():
    a = "git branch -r --merged | grep -v HEAD | xargs -L1 git --no-pager log --pretty=tformat:'%Cgreen%d%Creset %Cblue%ar%Creset' -1"
    t, r = cmd(a)
    print(t, r)
manlike
  • 45
  • 1
  • 11
  • 1
    Using pipes without `shell=True` requires a separate `subprocess.Popen` object per pipeline component. – Charles Duffy Nov 20 '20 at 20:33
  • 1
    Don't use the `command.split(" ")` to generate content to pass to `subprocess`-module functions -- it creates a whole passel of bugs. Much better to split your string **by hand**; you don't want `somecommand "my file with spaces"` to turn into `['somecommand', '"my', 'file', 'with', 'spaces"']`. – Charles Duffy Nov 20 '20 at 20:34
  • Directly on-point from the official documentation, wrt. making pipes work with `subprocess`: https://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline – Charles Duffy Nov 20 '20 at 20:36
  • 1
    ...it's important to note, by the way, that when a shell parses `--pretty=tformat:'%Cgreen%d%Creset %Cblue%ar%Creset'`, the single quotes are instructions **to that shell**, not passed as part of the argument to `git log`. It's exactly the same as `'--pretty=tformat:%Cgreen%d%Creset %Cblue%ar%Creset'`; the purpose of the quotes is to tell the shell to suppress word-splitting within them. – Charles Duffy Nov 20 '20 at 20:37
  • @CharlesDuffy That worked, thank you. – manlike Nov 20 '20 at 20:39

0 Answers0