Python subprocess.CalledProcessError:返回非零退出状态 2 [英] Python subprocess.CalledProcessError: returned non-zero exit status 2
问题描述
#!/usr/bin/env python
# encoding: utf-8
import re
import subprocess
import time
import json
def get_temperatures(disks):
sensors = subprocess.check_output(["sensors"])
temperatures = {match[0]: float(match[1]) for match in re.findall("^(.*?)\:\s+\+?(.*?)°C",
sensors, re.MULTILINE)}
for disk in disks:
output = subprocess.check_output(["smartctl", "-A", disk])
temperatures[disk] = int(re.search("Temperature.*\s(\d+)\s*(?:\([\d\s]*\)|)$",
output, re.MULTILINE).group(1))
return temperatures
def main():
while True:
print json.dumps(get_temperatures(("/dev/sda2", "/dev/sdb1")))
time.sleep(20)
if __name__ == '__main__':
main()
这是一个小脚本,可以使用smartmontools和lm-sensors监视Python中的温度.但是当我尝试运行它时,我遇到了错误
This is small script to monitor temperatures in Python, using smartmontools and lm-sensors. But when i try to run it i have a error
subprocess.CalledProcessError: Command '['smartctl', '-A', '/dev/sda2']' returned non-zero exit status 2
但是当我在终端中手动尝试此命令时,它们会很好用.
But when i try this command manually in terminal they work great.
一些信息:
uname -a
Linux LME 4.0.0-040000-generic #201504121935 SMP Sun Apr 12 23:36:33 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
推荐答案
如果您调用的进程返回了任何非零的退出代码,则会引发 CalledProcessError
.在命令行上,您应该 echo $?
以获取最后的返回码,并查看它是否确实返回了2.我怀疑它会返回.
A CalledProcessError
will be raised if any non-zero exit code is returned by your called process. On the command line, you should echo $?
to get the last return code and see if it really does return 2. I suspect it will.
如果这在您的python代码中还可以,那么您可以除了 CalledProcessError
之外,还可以从其属性中获取任何信息,尤其是 output
属性.(有关更多信息,请在 python文档中查找该错误.)
If that is okay in your python code, you can except the CalledProcessError
and get any information from within its attributes especially the output
attribute. (Look up this error in the python docs for more information.)
示例:
import subprocess
output = None
try:
output = subprocess.check_output(["smartctl", "-A", "/dev/sda2"])
except subprocess.CalledProcessError as e:
output = e.output
这篇关于Python subprocess.CalledProcessError:返回非零退出状态 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!