Python subprocess.run 在调用 "git remote" 时不会 return 作为标准输出的字符串
Python subprocess.run does not return a string as stdout when calling "git remote"
我正在制作一个程序来显示 git 遥控器,但这段代码只是 returns b''
>>> subprocess.run(
... "git remote",
... capture_output=True,
... shell=True,
... cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
... ).stdout
这个我也试过了,这个也是returns b''
:
>>> subprocess.run(
... "git remote",
... shell=True,
... cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
... ).stdout
在 PowerShell 中,此命令有效。
PS C:\Users\Andy\source\repos\PyPlus> git remote
origin
那么为什么这不起作用?感谢您的任何想法!
我在一个随机目录中对此进行了测试,似乎 return 进入了 stderr 而不是 stdout。所以这有效:
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'
编辑:
在 git 存储库文件夹中对其进行了测试,您解释的代码对我有用:
test = subprocess.run("git remote", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout
>>> test
b'origin\n'
也许另一个适合您的解决方案:
import os
test = os.popen("git remote").read()
我正在制作一个程序来显示 git 遥控器,但这段代码只是 returns b''
>>> subprocess.run(
... "git remote",
... capture_output=True,
... shell=True,
... cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
... ).stdout
这个我也试过了,这个也是returns b''
:
>>> subprocess.run(
... "git remote",
... shell=True,
... cwd=r'\Users\Andy\source\repos\PyPlus', stdout=subprocess.PIPE
... ).stdout
在 PowerShell 中,此命令有效。
PS C:\Users\Andy\source\repos\PyPlus> git remote
origin
那么为什么这不起作用?感谢您的任何想法!
我在一个随机目录中对此进行了测试,似乎 return 进入了 stderr 而不是 stdout。所以这有效:
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'
编辑: 在 git 存储库文件夹中对其进行了测试,您解释的代码对我有用:
test = subprocess.run("git remote", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout
>>> test
b'origin\n'
也许另一个适合您的解决方案:
import os
test = os.popen("git remote").read()