上下文:我试图找到一个python包的github存储库。为此,我使用zgrep'ping包存档的github url。它工作得很好,直到我限制输出1个结果:
# works, returns a lot of results
subprocess.check_output(["zgrep", "-oha", "github", 'Django-1.10.1.tgz']) # works, a lot of results
# add -m1 to limit output, returns status 2 (doesn't work)
subprocess.check_output(["zgrep", "-m1", "-oha", "github", 'Django-1.10.1.tgz']) # works, a lot of results
# same command, different file - works
subprocess.check_output(["zgrep", "-m1", "-oha", "github", 'grabber.py'])
在命令行中,这三个命令都可以正常工作。什么好主意吗?
回溯:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 574, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['zgrep', '-m1', '-oha', 'github', 'pkgs/Django-1.10.1.tar.gz']' returned non-zero exit status 2
命令行:
$ zgrep -m1 -oha "github.com/[^/]+/django" pkgs/Django-1.10.1.tar.gz
github.com/django/django
所以,原因是:zgrep是一个shell脚本,它只是通过gzip和egrep将归档文件管道化。如果我们限制结果的数量,egrep终止管道,因此gzip退出并抱怨。在控制台中,我们永远不会看到它,但是subprocess不知何故捕获了这个信号并引发异常。
解决方案:写一个迷你版的zgrep没有报错
gunzip < $FILE 2> /dev/null | egrep -m1 -ohia $PATTERN