linux / python

时间:2016-03-04 17:24:11

标签: python linux exception

假设我有以下执行流程:

       def method1:
          try:
            method2()
          except Exception as e:
            handle_exception()

        def method2:
          command = "<some linux command>"
          status = execute_command(command) 
          if status != 0:   
            log_exception()

        def execute_command(command):
            subprocess.popen(command, <other params>)

        method1()  

command.py

with open(path, 'w') as f: #this raises IOError
        #do something

是否会调用handle_exception()?我的理解是将打印回溯,因为异常不会渗透到method1。这是因为execute_command(..)将产生一个不同的进程,它将拥有自己的调用堆栈。我的理解是否正确?

2 个答案:

答案 0 :(得分:2)

The short answer: if you want the except block to run if you get a status code other then 0 then raise an error in method2:

  if (status != 0)   
    log_exception()
    raise RuntimeError("got non-0 exit code: %d"%status)

Long answer with examples: it is highly dependent on how you are executing the command, os.system only raises an error if you don't give it a str:

import os
... #def method1 and method2
execute_command = os.system
method1()

this would call log_exception() since <some linux command> isn't a valid command. But no error is raised so handle_exception() wouldn't be used. You could also use subprocess.call:

import subprocess
... #def method1 and method2
execute_command = subprocess.call
method1()

This way subprocess.call raises an error when it can't find an executable called <some linux command>, but with a valid executable and failing process:

import subprocess

... #def method1

def method2():
  command = ["python","-c","INVALID CODE !!"]
  status = subprocess.call(command)
  if(status !=0):
      print("got non-0 status:  %r"%status)

method1()

This way there was an error in the call and returned non-0 status but that doesn't raise any errors in python, if you want method2 to raise a python error for a non-0 exit status this is easy to do:

  if (status != 0)   
    log_exception()
    raise RuntimeError("got non-0 exit code: %d"%status)

答案 1 :(得分:-1)

不,它不会赢,并且不会打印回溯。实际上,用户不会看到任何可见的内容(前提是您修复了明显的语法错误)。