GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitCommandError: Cmd('git') failed due to: exit code(1) when execute 'grep' with regex · gitpython-developers/GitPython · Discussion #1164

GitCommandError: Cmd('git') failed due to: exit code(1) when execute 'grep' with regex #1164

Answered by rmahdav
rmahdav asked this question in Q&A
GitCommandError: Cmd('git') failed due to: exit code(1) when execute 'grep' with regex #1164
@rmahdav rmahdav
Oct 23, 2020 · 4 comments · 1 reply
Answered by rmahdav Return to top
Discussion options
  • Uh oh!

    There was an error while loading. Please reload this page.

  • Uh oh!

    There was an error while loading. Please reload this page.

rmahdav
Oct 23, 2020

Hi,

I am trying to execute a grep command with regex using the execute() function. A part of my code is:

for item in toggles:

    files_result = Repo.execute(["git", "grep", "--files-with-matches", "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\""]) 

I am getting the following error:

---------------------------------------------------------------------------
GitCommandError                           Traceback (most recent call last)
<ipython-input-82-f4329c19384f> in <module>
      3 
      4 for item in toggles:
----> 5     files_result = Repo.execute(["git", "grep", "--files-with-matches", "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\""])
      6     files = files_result.splitlines()
      7 

/opt/anaconda3/lib/python3.8/site-packages/git/cmd.py in execute(self, command, istream, with_extended_output, with_exceptions, as_process, output_stream, stdout_as_string, kill_after_timeout, with_stdout, universal_newlines, shell, env, max_chunk_size, **subprocess_kwargs)
    820 
    821         if with_exceptions and status != 0:
--> 822             raise GitCommandError(command, status, stderr_value, stdout_value)
    823 
    824         if isinstance(stdout_value, bytes) and stdout_as_string:  # could also be output_stream

GitCommandError: Cmd('git') failed due to: exit code(1)
  cmdline: git grep --files-with-matches "config.isEnabled([[:space:]*]'async-payments'[[:space:]*])"

However, when I run git grep --files-with-matches "config.isEnabled([[:space:]*]'async-payments'[[:space:]*])" in the command line, it works.

I appreciate any help.

You must be logged in to vote
All reactions
Answered by rmahdav Oct 23, 2020

The issue is resolved by removing \" from the "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\"".

Another issue comes up now. If the result of executing grep function is empty, I am getting the same error GitCommandError: Cmd('git') failed due to: exit code(1) . When there is any result, it works fine.

Any ideas to solve this?

View full answer

Replies: 4 comments · 1 reply

Comment options
  • Uh oh!

    There was an error while loading. Please reload this page.

Byron
Oct 23, 2020
Maintainer

It’s unlikely git is executed in the correct directory, which is why one would rather instantiate a Repo instance first along the lines of r = git.Repo(path). Then invoke git like r.git.grep("--files-with-matches", "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\""]).

Docs for how to invoke git, and here for the troubleshooting.

Please feel free to keep posting into the closed issue for follow ups.

You must be logged in to vote
All reactions
0 replies
Comment options
  • Uh oh!

    There was an error while loading. Please reload this page.

rmahdav
Oct 23, 2020
Author

Thanks for the response. Repo is my code came from Repo = git.Git(os.path.expanduser(path)), so the directory was correct. However, I did what you said but I am getting the same error.

---------------------------------------------------------------------------
GitCommandError                           Traceback (most recent call last)
<ipython-input-94-9b1915237b33> in <module>
      3 r = Repo(path)
      4 for item in toggles:
----> 5     files_result = r.git.grep("--files-with-matches", "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\"")
      6     #files_result = r.execute(["git", "grep", "--files-with-matches", "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\""])
      7     files = files_result.splitlines()

/opt/anaconda3/lib/python3.8/site-packages/git/cmd.py in <lambda>(*args, **kwargs)
    540         if name[0] == '_':
    541             return LazyMixin.__getattr__(self, name)
--> 542         return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
    543 
    544     def set_persistent_git_options(self, **kwargs):

/opt/anaconda3/lib/python3.8/site-packages/git/cmd.py in _call_process(self, method, *args, **kwargs)
   1003         call.extend(args)
   1004 
-> 1005         return self.execute(call, **exec_kwargs)
   1006 
   1007     def _parse_object_header(self, header_line):

/opt/anaconda3/lib/python3.8/site-packages/git/cmd.py in execute(self, command, istream, with_extended_output, with_exceptions, as_process, output_stream, stdout_as_string, kill_after_timeout, with_stdout, universal_newlines, shell, env, max_chunk_size, **subprocess_kwargs)
    820 
    821         if with_exceptions and status != 0:
--> 822             raise GitCommandError(command, status, stderr_value, stdout_value)
    823 
    824         if isinstance(stdout_value, bytes) and stdout_as_string:  # could also be output_stream

GitCommandError: Cmd('git') failed due to: exit code(1)
  cmdline: git grep --files-with-matches "config.isEnabled([[:space:]*]'async-payments'[[:space:]*])"
You must be logged in to vote
All reactions
0 replies
Comment options
  • Uh oh!

    There was an error while loading. Please reload this page.

rmahdav
Oct 23, 2020
Author

The issue is resolved by removing \" from the "\"config.isEnabled([[:space:]*]'" + item + "'[[:space:]*])\"".

Another issue comes up now. If the result of executing grep function is empty, I am getting the same error GitCommandError: Cmd('git') failed due to: exit code(1) . When there is any result, it works fine.

Any ideas to solve this?

You must be logged in to vote
All reactions
0 replies
Answer selected by Byron
Comment options
  • Uh oh!

    There was an error while loading. Please reload this page.

Byron
Oct 23, 2020
Maintainer

By the looks of it, there is no way to ignore a non-zero exit code nor does git grep allow to ignore empty results.

As you are effectively executing the git program, maybe it’s easiest to call git yourself.

You must be logged in to vote
All reactions
1 reply
@glensc
Comment options
  • Uh oh!

    There was an error while loading. Please reload this page.

  • Uh oh!

    There was an error while loading. Please reload this page.

glensc Nov 17, 2025

Here's my "trick" to catch exit code 1

        try:
            return self.repo.git.grep("-l", pattern)
        except GitCommandError as exc:
            # git grep exits with status 1 when there are no matches; treat as an empty result
            if exc.status == 1:
                return []
            # Re-raise unexpected git errors
            raise
All reactions
  • 👍 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
3 participants
@rmahdav @Byron @glensc
Converted from issue

This discussion was converted from issue #1074 on February 26, 2021 11:18.

You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.