【发布时间】:2015-10-12 05:25:29
【问题描述】:
我正在用 Python 编写一个脚本程序。在这个程序中,我需要获取文件名的 grep 结果并从中提取文件名。 我现在被'grep'困住了。 我尝试 grep 一个名为 NoMoreHotCorner_20151006.T 的文件并返回结果。 我的预期结果应该如下:
grep: command/CVS: Is a directory
grep: command/obsolete: Is a directory
command/yosemite-2015.K:#p system/NoMoreHotCorner_20151006.T
我可以保证这个文件存在,我的路径没有问题。
我可以通过使用 os.system() 得到想要的结果。
>>> import os
>>> from subprocess import Popen, PIPE
>>> from subprocess import CalledProcessError, check_output
>>> string = 'grep '+'NoMoreHotCorner_20151006.T'+' command/*'
>>> os.system(string)
grep: command/CVS: Is a directory
grep: command/obsolete: Is a directory
command/yosemite-2015.K:#p system/NoMoreHotCorner_20151006.T
但此函数无法将其输出返回到屏幕。所以我决定改用 subprocess.check_output 。但它引发了 CalledProcessError。
>>> p = check_output(string,shell=True)
grep: command/CVS: Is a directory
grep: command/obsolete: Is a directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'grep NoMoreHotCorner_20151006.T command/*' returned non-zero exit status 2
所以我在堆栈溢出时查找了类似的问题并处理了这次异常。但它只打印前两行....
>>> try:
... p = check_output(string,shell=True)
... except CalledProcessError as e:
... print(e.returncode)
...
grep: command/CVS: Is a directory
grep: command/obsolete: Is a directory
2
所以我这次改用 Popen。但是,它仍然存在问题。在它输出前两行之后,它会永远运行。
>>> p = Popen(string,shell=True,stdout=PIPE)
>>> grep: command/CVS: Is a directory
grep: command/obsolete: Is a directory
KeyboardInterrupt
我完全被困在这一点上。
【问题讨论】: