import os
import signal
import sys

import click
import gevent

import pyinfra

from .legacy import run_main_with_legacy_arguments
from .main import cli, main


# Set CLI mode
pyinfra.is_cli = True

# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True

# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')

# Shut it click
click.disable_unicode_literals_warning = True  # noqa

# Force line buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1)


def _handle_interrupt(signum, frame):
    click.echo('Exiting upon user request!')
    sys.exit(0)


gevent.signal_handler(signal.SIGINT, gevent.kill)  # kill any greenlets on ctrl+c
signal.signal(signal.SIGINT, _handle_interrupt)  # print the message and exit main


def execute_pyinfra():
    # Legacy support for pyinfra <0.4 using docopt
    if '-i' in sys.argv:
        run_main_with_legacy_arguments(main)
    else:
        cli()


if __name__ == 'pyinfra_cli.__main__':
    execute_pyinfra()

@@ -669,16 +669,60 @@
 it(0)%0A%0A%0A
+try:%0A    # Kill any greenlets on ctrl+c%0A    
 gevent.s
@@ -766,40 +766,113 @@
 ill)
-  # kill any greenlets on ctrl+c
+%0Aexcept AttributeError:%0A    # Legacy (gevent %3C1.2) support%0A    gevent.signal(signal.SIGINT, gevent.kill)%0A
 %0Asig

Fix support for older gevent versions.