2014-02-27 12 views
0

我有一些運行Windows命令的Python 2.7代碼。如果該命令成功,則返回輸出。 (更具體地說,它搜索多行輸出中的搜索詞,然後返回具有該搜索詞的行)。如何查看check_output中的異常輸出

如果命令失敗,它只是返回「錯誤」

我想修改此代碼返回實際的錯誤消息。如何使我的函數的「異常」部分返回由命令輸出的實際錯誤消息?

def myFunction(machineName): 
try: 
    output = subprocess.check_output('command ' + machineName) 
    for line in output.split('\n'): 
     if 'TextToSearchFor' in line: 
      return line 
except subprocess.CalledProcessError: 
    return "Error" 
return 

回答

0

設置並獲得subprocess.CalledProcessError.message。通過這種方式,當錯誤不被處理時顯示消息,並且如果有其他程序員可能會使用該異常,那麼編程就是很好的方法。

0

該文件實際上有an example那:在呼叫中使用stderr=subprocess.STDOUT

它還提到subprocess.CalledProcessError有一個output屬性包含從過程的任何輸出(我假設這是stdout,但或許也stderr,在這種情況下,你不需要設置stderr呼叫本身)。

因此,你應該能使用(未經測試):

try: 
    output = subprocess.check_output('command ' + machineName) 
    for line in output.split('\n'): 
     if 'TextToSearchFor' in line: 
      return line 
except subprocess.CalledProcessError: 
    print subprocess.CalledProcessError.output 
    return "Error" 
return 
0

您可以使用例外:

def myFunction(machineName): 
    try: 
     output = subprocess.check_output('command ' + machineName) 
     for line in output.split('\n'): 
      if 'TextToSearchFor' in line: 
       return line 
    except Exception, e: 
     print e 
     return "Error" 
    return 

如果你有興趣的堆棧跟蹤,你可以這樣做:

import trace 

at except Exception,e:你可以加

traceback.print_exc() 
0

小心 - 你捕獲的異常是不是唯一的例外,你可能會想到:

>>> import subprocess 
>>> try: 
...  output = subprocess.check_output("nosuch") 
... except Exception as e: 
...  print str(e) 
... 
[Errno 2] No such file or directory 
>>> e 
OSError(2, 'No such file or directory') 
>>> type(e) 
<type 'exceptions.OSError'> 

還要注意的是接口的功能意味着你必須做出錯誤專項檢查,導致在你的邏輯清晰的損失,因爲每次調用必須像:

result = myFunction(someArg): 
if result.startswith("error"): 
    # handle issue somehow 
else: 
    # normal logic flow to do something with result 

它實際上是更簡單的通過去除誤差從功能檢查和處理在調用由此產生的異常處理在適當的點異常。然後,您的代碼看起來像

try: 
    # normal logic flow to do something with result 
except (tuple, of, exceptions) as e: 
    # handle issue somehow 

還要注意異常可以轉換爲dtrings,通常給你任何相關的錯誤信息,如在開放的例子,所以這是真正的回答你的問題。

如果您的Python已經足夠近了,您應該使用except ... as name:格式而不是except ..., name:,因爲它會在不更改的情況下遷移到Python 3。