Python 2.4 subproces.CalledProcessError替代

时间:2015-02-26 15:36:01

标签: python python-2.4 python-2.3

我正在尝试向我的子流程添加try/except

        try:
            mountCmd = 'mount /dev/%s %s%s' % (splitDevice, homeDir, splitDevice)
            dev = '/dev/%s' % splitDevice
            subprocess.check_call(mountCmd, shell=True)
        except subprocess.CalledProcessError:
            continue

上面的snipet有效,但如果主机在2.5以下的Python版本上执行代码,则代码将失败,因为在Python 2.5版中引入了CalledProcessError

有人知道我可以用于CalledProcessError模块的替代品吗?

编辑: 这就是我解决问题的方法

        mountCmd = 'mount /dev/%s %s%s' % (splitDevice, homeDir, splitDevice)
        dev = '/dev/%s' % splitDevice
        returnCode = 0
        #CalledProcessError module was introduced in version 2.5 of python. If older version do the following.
        if sys.hexversion < 0x02050000: 
            try:
                p3 = subprocess.Popen(mountCmd, shell=True, stdout=subprocess.PIPE)
                output = p3.communicate()[0]
                returnCode = p3.returncode
            except:
                pass
            if returnCode != 0:
                continue
        else: #If version of python is newer than 2.5 use CalledProcessError.
            try:
                subprocess.check_call(mountCmd, shell=True)
            except subprocess.CalledProcessError, e:
                continue

1 个答案:

答案 0 :(得分:1)

  

exception subprocess.CalledProcessError

Exception raised when a process run by check_call() or check_output() returns a non-zero exit status.

returncode

    Exit status of the child process.

cmd

    Command that was used to spawn the child process.

output

    Output of the child process if this exception is raised by check_output(). Otherwise, None.

Source。这意味着您需要检查check_all或check_output运行的进程是否具有非零输出。