3

我正在尝试将 a 添加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

上面的代码片段有效,但如果主机在低于 2.5 的 Python 版本上执行代码,则代码将失败,因为CalledProcessError它是在 Python 2.5 版本中引入的。

有人知道我可以为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
4

1 回答 1

1

异常 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.

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

于 2015-02-26T15:41:56.000 回答