在Python中为Awk使用子进程

2024-04-19 04:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从Python文件中运行这个命令git status -vv | awk 'NR>5 {print $0}'。但是我不能让awk命令工作

下面是我的git st的一个示例结果:

# On branch master
# Your branch is ahead of master by 2 commits.
#
#
#       modified:   file1
#       modified:   file2
#       modified:   file3

当我从终端运行命令时,我得到了我想要的:

#       modified:   file1
#       modified:   file2
#       modified:   file3

我在Python脚本中实现它时遇到问题:

import sys
import subprocess as sb

ps = sb.Popen(("git","status","-vv"),stdout=sb.PIPE)
output = sb.check_output(('awk','"NR>5 {print $0}"'),stdin=ps.stdout)
print output

但是,这只返回git st结果,而不返回行上执行的awk。如何从python中执行此操作以获得与在终端中运行时相同的输出


Tags: git命令masterbranchoutputstatusfile1nr
2条回答

以下代码应该可以工作(只需删除awk参数的双引号)

import sys
import subprocess as sb

ps = sb.Popen(("git","status","-vv"),stdout=sb.PIPE)
output = sb.check_output(('awk','NR>5 {print $0}'),stdin=ps.stdout)
print output

这可能要简单得多:

#!/usr/bin/python3                                                                                                                                                                 

import sys
import subprocess as sb

cmd = "git status -vv | awk '(NR>5){ print $0 }'"

output = sb.check_output(cmd, stderr=sb.STDOUT, shell=True)
sys.stdout.write('{}'.format(output))

相关问题 更多 >