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!
asked May 25, 2021 at 8:51
ZCGCoder
5422 gold badges11 silver badges31 bronze badges
1 Answer 1
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()
answered May 25, 2021 at 8:58
mnikley
1,6631 gold badge11 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
MisterMiyagi
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.mnikley
youre right - works as intended. I think the comment from @PSKP is more suitable anyway
ZCGCoder
Got it. I’ll change the cwd attribute.
lang-py
stdoutto not fail withValueError) correctly returnb'origin\n'in a git repository.