2017-10-18 181 views
0

我使用subprocess.check_output命令爲兩個不同的命令,並在一種情況下,我得到了一個subprocess.CalledProcessError,在另一種情況下,不是,但程序崩潰。該gpio482文件夾不存在與設定方法返回錯誤和get方法崩潰是捕獲異常蟒蛇子進程異常

Get方法:

try: 
    subprocess.check_output("echo 0 > /sys/class/gpio/gpio482/value", shell=True) 
except subprocess.CalledProcessError: 
    log("set state failed.") 
    return "not-writable" 

Get方法是崩潰了:

try: 
    state_string = subprocess.check_output("cat /sys/class/gpio/gpio482/value", shell=True) 
except subprocess.CalledProcessError: 
    log("Get state failed.") 
    return "integer", "0" # unknown 

有我做錯了什麼?

如果我運行shell的commonds我得到了同樣的錯誤消息:

>>> subprocess.check_output("cat /sys/class/gpio/gpio482/value", shell=True) 
cat: can't open '/sys/class/gpio/gpio482/value': No such file or directory 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output 
raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command 'cat /sys/class/gpio/gpio482/value' 
returned non-zero exit status 1 
>>> 
>>> 
>>> subprocess.check_output("echo 0 > /sys/class/gpio/gpio482/value", 
shell=True) 
/bin/sh: /sys/class/gpio/gpio482/value: No such file or directory 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output 
raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command 'echo 0 > 
/sys/class/gpio/gpio482/value' returned non-zero exit status 1 
+0

你得到了什麼錯誤信息? –

+0

如果我在shell上嘗試兩行,我得到了相同的錯誤消息。 – fresh

+0

無法重現你的情況,你確定你的程序已經處理了'CalledProcessError' –

回答

0

兩個功能如下所示。 set函數可以正常工作,並且捕獲異常,但是在get函數中我崩潰了。

def get_uid_light_state(): 
log("get_uid_light_state") 

try: 
    state_string = subprocess.check_output("cat /sys/class/gpio/gpio482/value", shell=True) 
except subprocess.CalledProcessError: 
    log("Get state failed.") 
    return "integer", "0" 

if state_string == "1\n": 
    return "integer", "2" 
elif state_string == "0\n": 
    return "integer", "1" 

def set_uid_light_state(snmptype, state): 
if snmptype != "integer": 
    return "wrong-type" 

if state == "1": 
    cmd_set_state = "echo 0 > /sys/class/gpio/gpio482/value" 
elif state == "2": 
    cmd_set_state = "echo 1 > /sys/class/gpio/gpio482/value" 
else: 
    log("Invalid value for set uid light state") 
    return "wrong-value" 

try: 
    subprocess.check_output(cmd_set_state, shell=True) 
except subprocess.CalledProcessError: 
    log("Set state failed.") 
    return "not-writable" 

return "DONE"