python exception handling is not working with fabric.api

I am working on a code so that it can handle the error from fabric.local, but some how it always abort with the error and never go into except block. Here is my code, hopefully can get some idea from you guys

This snippet is trying to get Vagrant ssh port, if the vagrant is not up, bring it up

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]]

Error

[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'

UPDATE Similar Question and Answer

Can I catch error codes when using Fabric to run() calls in a remote shell?


It seems like it's just a warning from fabric. My understand if you encounter an error on ssh, it doesn't "translate" into a Python error, that's why the exception block doesn't work. Please provide error trace for further analysis.

python, logging.exception will output the traceback after you catch the error: from fabric.​api import settings with settings(warn_only=True): p = run('sudo foo') if p.​return_code It is easy to not have the traceback display on the screen, but Im not sure I recommend avoiding python exception handling is not working with fabric.api  Catching Exceptions in Python. In Python, exceptions can be handled using a try statement. A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. It is up to us, what operations we perform once we have caught the exception.


Martin is correct, that was a warning from fabric.api.local and python exception handling will not treat it as an error. Instead, the error that I seen was from another part of code which the above snippet had returned something invalid. Instead of using try and except, if else is used with return_code which checking the command exit status.

port = local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True)
if port.return_code == 0:
    return port
else:
    with lcd('%s' % (buildfolder)):
            local('vagrant up {}'.format(env.vmId), capture=True)
        return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))

Save Lono » How to handle Python 3 Fabric exceptions with a , How to handle Python 3 Fabric exceptions with a Decorator. Python's Fabric from fabric.api import * The first time it works with no problem. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. Handling an exception If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block.


Your problem is probably here.

with settings(warn_only=True)

Remove this line, and your local call will raise exceptions if the command exits with a non-zero return code.

def task_name():
    with settings(warn_only=True):
        try:
            local("invalid_command")
        except:
            print("This will never print!")

Lets compare that to;

def task_name():
    try:
        local("invalid_command")
    except:
        print("This will print")

Use real exceptions for errors · Issue #277 · fabric/fabric · GitHub, bitprophet opened this issue on Aug 18, 2011 · 5 comments It should be possible to move from the current, kind of ugly error handling to real exceptions (​i.e. so that wherever we call a friendly error message like we currently print, instead of a Python stack trace. Contact GitHub · Pricing · API · Training · Blog · About. For now (version <= 2.4) exception doesn't have to be inherited from Exception. Thus plain 'except:' catches all exceptions, not only system. String exceptions are one example of an exception that doesn't inherit from Exception. -- MikeRovner. I believe that as of 2.7, exceptions still don't have to be inherited from Exception or even BaseException.


Problems with the using of `run` function with fabric 1.14 · Issue , These days, I have been using fabric version:1.14 to do some opertions, but encounter the issue. when executing the run method, it throw SymtemExit exception. from fabric.api import local, lcd, cd, run, env env.hosts  Note. Do not compare the return value to a specific exception; use PyErr_ExceptionMatches() instead, shown below. (The comparison could easily fail since the exception may be an instance instead of a class, in the case of a class exception, or it may be a subclass of the expected exception.)


exceptions, __weakref__ ¶. list of weak references to the object (if defined). exception fabric.​exceptions. InvalidV1Env ¶. Raised when attempting to import a Fabric 1 env  To use exception handling in Python, you first need to have a catch-all except clause. The words "try" and "except" are Python keywords and are used to catch exceptions. try-except [exception-name] (see above for examples) blocks The code within the try clause will be executed statement by statement.


Upgrading from 1.x, Python 3 compatibility (specifically, we now support 2.7 and 3.4+);; Thread-safe - no from fabric.api import env, run from fabric2 import Connection env.​host_string it into Paramiko; modern Fabric prefers to just let you handle Paramiko-level parameters directly. Most sections are broken down in table form, as follows:  After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options: raise allows you to throw an exception at any time. assert enables you to verify if a certain condition is met and throw an exception if it isn’t.