Search code examples
pythongitcmdsplit

Problem with split a cmd string in python


The cmd.split() does not work:

cmd = f'git log --all --grep="fixed bug" --pretty="%H|%an"'
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Generate this error:

enter image description here

With this code instead it works.

cmd = f'git log --reverse --pretty=format:"%H|%an|%at"'

It is not a problem of "bugs" because leaving only "fixed" does not generate anything. In addition, these 2 words are present in commits. I'm afraid it's a "--grepp" problem.


Solution

  • Split, splits using spaces as separators.

    In [2]: cmd = f'git log --all --grep="fixed bug" --pretty="%H|%an"'
    
    In [3]: cmd.split()
    Out[3]: ['git', 'log', '--all', '--grep="fixed', 'bug"', '--pretty="%H|%an"']
    

    So the command that gets executed is something like:

    git log --all --grep=fixed bug --pretty="%H|%an"

    which is not valid since 'fixed bug' are taken as 2 different arguments

    The preferred solution seems to be using shlex.split function instead that takes this into account.

    In [5]: shlex.split(cmd)
    Out[5]: ['git', 'log', '--all', '--grep=fixed bug', '--pretty=%H|%an']