【问题标题】:Python 2.4 subproces.CalledProcessError substitutePython 2.4 subprocess.CalledProcessError 替代品
【发布时间】:2015-04-29 01:43:12
【问题描述】:

我正在尝试将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 版本上执行代码,则代码将失败,因为在 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

【问题讨论】:

    标签: python python-2.4 python-2.3


    【解决方案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.
    

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

    【讨论】:

    • 我应该使用 Popen 而不是 check_call() 吗?波纹管与 check_call 有关:'注意不要将 stdout=PIPE 或 stderr=PIPE 与此功能一起使用,因为这可能会基于子进程输出量而死锁。当你需要管道时,将 Popen 与communicate() 方法一起使用。'
    • 这听起来像是个主意。任何使您能够获得过程结果的策略都应该或多或少地解决问题,但如果我是你,我只会将此代码应用于旧 Python。新的 Python 应该使用所有可能的功能。
    • 问题是我不知道将使用哪个版本的python,但我同意我可能会添加一些东西,首先检查python版本是否为2.5或更高,然后选择使用什么。谢谢,当我有机会对此进行测试时,我会更新我的帖子。
    • 您可以确定正在使用的版本。看看这篇文章:stackoverflow.com/questions/1093322/…
    • 感谢@lajos 的帮助,我也实现了版本检查。
    猜你喜欢
    • 2014-05-17
    • 2011-04-28
    • 2010-11-29
    • 2017-01-18
    • 2018-08-27
    • 2021-02-11
    • 2023-03-26
    • 2010-12-24
    • 2013-04-14
    相关资源
    最近更新 更多