首页 > 解决方案 > python异常处理不适用于fabric.api

问题描述

我正在编写一个代码,以便它可以处理来自 的错误fabric.local,但是它总是会因错误而中止并且永远不会进入except阻塞状态。这是我的代码,希望能从你们那里得到一些想法

此代码段正在尝试获取 Vagrant ssh 端口,如果 vagrant 未启动,请将其启动

def findsshport():
    with settings(warn_only=True):
        try:
            print 'greping port'
            return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
        except:
            print 'vagrant not up'
            with lcd('%s' % (buildfolder)):
                local('vagrant up ext4')
            return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))

env.user = 'root'
sshPort = findsshport()
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]

错误

[localhost] local: vagrant ssh-config 22921a7 | grep Port

Warning: local() encountered an error (return code 1) while executing 'vagrant ssh-config 22921a7 | grep Port'
Traceback (most recent call last):
  File "/home/testing/local/lib/python2.7/site-packages/test123/fabriclogin.py", line 114, in sshlogin
    env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
AttributeError: 'NoneType' object has no attribute 'split'

更新 类似的问题和答案

在远程 shell 中使用 Fabric to run() 调用时,我可以捕获错误代码吗?

标签: pythonvagrantfabric

解决方案


似乎这只是来自面料的警告。我知道如果您在 ssh 上遇到错误,它不会“转换”为 Python 错误,这就是异常块不起作用的原因。请提供错误跟踪以供进一步分析。


推荐阅读