【发布时间】:2016-07-11 05:50:21
【问题描述】:
我需要计算 Python 脚本中 shell 命令输出的行数。
这个函数在有输出的情况下可以正常工作,但如果输出为空,它会给出一个错误,如错误输出中所述。
如果命令的输出是None,我试图避免使用if 语句,但这没有帮助。
#!/usr/bin/python
import subprocess
lines_counter=0
func="nova list | grep Shutdown "
data=subprocess.check_output(func, shell=True)
if data is True:
for line in data.splitlines():
lines_counter +=1
print lines_counter
错误输出:
data=subprocess.check_output(func, shell=True)
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'nova list | grep Shutdown ' returned non-zero exit status 1
【问题讨论】:
标签: python command-line subprocess