1

I am making a program to show git remotes, but this code just returns b''

>>> subprocess.run(
...                 "git remote",
...                 capture_output=True,
...                 shell=True,
...                 cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
...                 ).stdout

I also tried this, and this also returns b'':

>>> subprocess.run(
...                 "git remote",
...                 shell=True,
...                 cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
...                 ).stdout

In PowerShell, this command works.

PS C:\Users\Andy\source\repos\PyPlus> git remote
origin

So why this does not work? Thanks for any ideas!

2
  • 1
    check this answer stackoverflow.com/questions/61956345/… Commented May 25, 2021 at 9:01
  • 1
    I cannot reproduce the issue with the code shown. Both approaches (the first needs removing stdout to not fail with ValueError) correctly return b'origin\n' in a git repository. Commented May 25, 2021 at 9:05

1 Answer 1

3

I tested this in a random directory and it seems like the return goes into stderr instead of stdout. So this worked:

test = subprocess.run("git remote", shell=True, stderr=subprocess.PIPE).stderr
>>> test
b'fatal: not a git repository (or any of the parent directories): .git\n'

Edit: tested it in a git repository folder and your explained code worked for me:

test = subprocess.run("git remote", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout
>>> test
b'origin\n'

Maybe another solution which works for you:

import os

test = os.popen("git remote").read()
Sign up to request clarification or add additional context in comments.

3 Comments

When the directory is not random but in fact a git repository, the output does not got to stderr but instead to stdout. That fatal error goes to stderr is to be expected, but not the use-case of the question.
youre right - works as intended. I think the comment from @PSKP is more suitable anyway
Got it. I’ll change the cwd attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.