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!

Andy Zhang
  • 198
  • 4
  • 21
  • 1
    check this answer https://stackoverflow.com/questions/61956345/how-to-interact-with-an-external-program-in-python-3/61956620#61956620 – PSKP May 25 '21 at 09: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. – MisterMiyagi May 25 '21 at 09:05

1 Answers1

2

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()
mnikley
  • 1,625
  • 1
  • 8
  • 21
  • 1
    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. – MisterMiyagi May 25 '21 at 09:01
  • 1
    youre right - works as intended. I think the comment from @PSKP is more suitable anyway – mnikley May 25 '21 at 09:04
  • Got it. I’ll change the cwd attribute. – Andy Zhang May 25 '21 at 13:35