【问题标题】:Git commands output in a file using python in Windows 10在 Windows 10 中使用 python 在文件中输出 Git 命令
【发布时间】:2021-08-19 02:54:54
【问题描述】:

我在努力

git status *> test.txt 

这在 powershell 中运行良好,但如果我使用 python 执行此操作 -

os.system('git status'+' *> '+log_path+'\git_output.txt')

fatal: '*' 似乎不是 git 存储库 致命:无法从远程存储库读取。

os.system('git status'+' 2> '+log_path+'\git_output.txt')

顺便说一句,这行得通!但我想要文件中的各种输出!

最好的方法是什么?

【问题讨论】:

  • Powershell 可能会插入 *
  • 请注意,Git 本身有些不寻常,因为它经常将“正常”输出写入其标准错误输出(C 代码中的文件描述符 2,Python 中的 os.stderr)。作为mklelement0 notes in a comment,这里的问题是os.system 没有使用 PowerShell。考虑使用subprocess.Popen 来捕获标准输出和标准错误。
  • @dan1st 但是有什么选项可以使用 *> 强制指定它的确切意图吗?
  • 你可以在powershell中显式运行命令。
  • 也有相关的,有更多的链接以获得更多的背景阅读:stackoverflow.com/q/34186035/1256452

标签: python git powershell


【解决方案1】:

此实现捕获结果并将它们写入文件:

output_file = open('git_output.txt', 'w')
output_file.write(os.popen('git status').read())
output_file.close()

虽然它不捕获错误(stderr 输出)。

【讨论】:

  • OP 唯一的问题是重定向 (>) syntax 问题:os.system() 调用 cmd.exe 作为默认 shell,它不理解 PowerShell-only *> 重定向。使用cmd.exe-适当的重定向语法,os.system() 在这种情况下工作得很好。您的代码也没有捕获 stderr,其中的包含是 OP 的意图。
  • @AdityaSinha,不,这种方法不会捕获错误(stderr 输出)。 Joep,我很高兴您重视我的评论,但请考虑直接修改您的答案。
【解决方案2】:

看看redirection from command prompt(不同于powershell)

os.system('git status'+' 1> '+log_path+'\git_output.txt 2>&1')

【讨论】:

  • 这就像一个魅力!谢谢丹尼尔。
猜你喜欢
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2020-01-01
  • 2012-06-22
  • 2017-05-23
  • 2016-04-21
相关资源
最近更新 更多