Python 2.4 subprocess.CalledProcessError替代方案

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

以上片段有效,但如果主机在Python版本低于2.5的情况下执行代码,则代码将失败,因为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
1个回答

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.

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


我应该使用Popen而不是check_call()吗?以下内容与check_call有关:“注意:不要在此函数中使用stdout=PIPE或stderr=PIPE,因为这可能会基于子进程输出量导致死锁。当您需要管道时,请使用带有communicate()方法的Popen。” - Adilicious
听起来像是个好主意。任何能够让你获得流程结果的策略应该差不多都能解决问题,但如果我是你,我只会将此代码应用于旧版 Python。新版 Python 应该使用所有可能的精华特性。 - Lajos Arpad
问题在于我不知道将使用哪个版本的Python,但我同意我可能会添加一些内容,首先检查Python版本是否为2.5或更高版本,然后选择要使用的内容。谢谢,我会在有机会测试时更新我的帖子。 - Adilicious
1
你可以确定正在使用的版本。查看这个帖子:https://dev59.com/ZXNA5IYBdhLWcg3wGJwV - Lajos Arpad
感谢 @lajos 的帮助,我也已经实现了版本检查。 - Adilicious
好奇问一下:需要使用Python 2.4的是什么样的系统呢? :) - Dr. Jan-Philip Gehrcke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接