예제 #1
0
def create_diff(new, old, context=10, color=False):
    if not color:
        crayons.disable()

    fromfiledate = old['time'].strftime("%Y-%m-%d %H:%M:%S")
    tofiledate = new['time'].strftime("%Y-%m-%d %H:%M:%S")

    for diff in colordiff(json.dumps(old['configuration'],
                                     indent=2).splitlines(),
                          json.dumps(new['configuration'],
                                     indent=2).splitlines(),
                          fromfile='{}/configuration'.format(old['arn']),
                          tofile='{}/configuration'.format(new['arn']),
                          fromfiledate=fromfiledate,
                          tofiledate=tofiledate,
                          n=context,
                          lineterm=''):
        yield diff

    for diff in colordiff(json.dumps(old['relationships'],
                                     indent=2).splitlines(),
                          json.dumps(new['relationships'],
                                     indent=2).splitlines(),
                          fromfile='{}/relationships'.format(old['arn']),
                          tofile='{}/relationships'.format(new['arn']),
                          fromfiledate=fromfiledate,
                          tofiledate=tofiledate,
                          n=context,
                          lineterm=''):
        yield diff
예제 #2
0
def main():
    """Runtime code. Always indent a function"""
    # print 'red string' in red
    print(crayons.red('red string'))

    # Red White and Blue text
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.disable()  # disables the crayons package
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.DISABLE_COLOR = False  # enable the crayons package

    # This line will print in color because color is enabled
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    # print 'red string' in red
    print(crayons.red('red string', bold=True))

    # print 'yellow string' in yellow
    print(crayons.yellow('yellow string', bold=True))

    # print 'magenta string' in magenta
    print(crayons.magenta('magenta string', bold=True))

    # print 'white string' in white
    print(crayons.white('white string', bold=True))
예제 #3
0
def main():
    print(crayons.red('red string'))
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))
    crayons.disable()
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.DISABLE_COLOR = False
예제 #4
0
def command_line_runner():
    parser = get_parser()
    args = vars(parser.parse_args())

    if args['version']:
        print('synonym=={}'.format(__version__))
        return

    if args['clear_cache']:
        _clear_cache()
        print(crayons.red('\nCache cleared successfully.\n'))
        return

    if not args['query']:
        parser.print_help()
        return

    if not os.getenv('SYNONYM_DISABLE_CACHE'):
        _enable_cache()

    if not args['color']:
        crayons.disable()

    if sys.version < '3':
        print(synonym(args).encode('utf-8', 'ignore'))
    else:
        print(synonym(args))
예제 #5
0
파일: pruner.py 프로젝트: thundeR2GE/pruner
    def _loadArgs(self):
        self.reqFile = self.args.requirements_file
        self.outputFile = self.args.output_file
        self.testCommand = self.args.test_command

        if self.args.nocolor:
            crayons.disable()
예제 #6
0
def main():
    # Handle fs weirdness
    monkey.patch_fs()

    # Disable terminal colors if NO_COLOR is set
    if os.environ.get('NO_COLOR'):
        import crayons
        crayons.disable()

    # Global exception handler for KeyboardInterrupt
    sys.excepthook = ctrlc_excepthook

    # Create base parser and subparsers
    parser = argparse.ArgumentParser(
        prog='fw', description='Flywheel command-line interface')

    # Add commands from commands module
    add_commands(parser)

    # Parse arguments
    args = parser.parse_args()

    # Additional configuration
    config_fn = getattr(args, 'config', None)
    if callable(config_fn):
        config_fn(args)

    log.debug('CLI Version: %s', util.get_cli_version())
    log.debug('CLI Args: %s', sys.argv)
    log.debug('Platform: %s', platform.platform())
    log.debug('System Encoding: %s', sys.stdout.encoding)
    log.debug('Python Version: %s', sys.version)

    func = getattr(args, 'func', None)
    if func is not None:
        # Invoke command
        try:
            rc = args.func(args)
            if rc is None:
                rc = 0
        except flywheel.ApiException as e:
            log.debug('Uncaught ApiException', exc_info=True)
            if e.status == 401:
                perror('You are not authorized: {}'.format(
                    e.detail or 'unknown reason'))
                perror(
                    'Maybe you need to refresh your API key and login again?')
            else:
                perror('Request failed: {}'.format(e.detail or e))
            rc = 1
        except Exception as e:
            log.debug('Uncaught Exception', exc_info=True)
            perror('Error: {}'.format(e))
            rc = 1
    else:
        parser.print_help()
        rc = 1

    sys.exit(rc)
예제 #7
0
def main():
    #print 'red string' in red
        print(crayons.red('red string'))
#RWB txt
        print('{}white {}'.format(crayons.red('red'), crayons.blue("blue")))
        crayons.disable()
        print('{}white{}'.format(crayons.red('red'), crayons.blue('blue')))
        print(crayons.red('red string', bold = true))
예제 #8
0
def main ():
    print(crayons.red('red string'))
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.disable()
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.DISABLE_COLOR = False

    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    print(crayons.red('red string', bold=True))

    print(crayons.yellow('yellow string', bold=True))

    print(crayons.magenta('magenta string', bold=True))

    print(crayons.white('white string', bold=True))
예제 #9
0
def parse_args(args) -> Namespace:
    parser = ArgumentParser(description=DESC, )
    parser.add_argument('bump', type=str.lower, nargs='?', choices=SEMVER_NUMS)
    parser.add_argument(
        '--preview', '-p', action='store_true',
        help='Display a preview of changes'
    )
    parser.add_argument(
        '--no-tag', '-n', action='store_true',
        help='Prevents git from creating new tags'
    )
    parser.add_argument(
        '--yes', '-y', action='store_true',
        help='Auto confirms all confirmation prompts'
    )
    parser.add_argument(
        '--message', '-m', type=str, metavar='', default='version {}',
        help='Message for tag annotation'
    )
    parser.add_argument(
        '--version', action='store_true',
        help='shows currently installed version'
    )
    parser.add_argument(
        '--no-color', action='store_true', help='disables coloured output'
    )
    parser.add_argument(
        '--files', '-f', type=FileType('r'), nargs='*',
        help='list of file names to find and replace version number'
    )
    args = parser.parse_args(args)
    if args.no_tag and args.files is None:
        parser.error('--files are required when --no-tag is set')

    # Disable all colour if flags are present
    if args.no_color:
        crayons.disable()

    # Handle version flag
    if args.version:
        print("Current version:", __version__)
        sys.exit(0)

    return args
예제 #10
0
파일: color1.py 프로젝트: denisavila/mycode
import crayons

# print 'red string' in red
print(crayons.red('red string'))

# Red White and Blue text
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.disable()  # disables the crayons package
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.DISABLE_COLOR = False  # enable the crayons package

# This line will print in color because color is enabled
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

# print 'red string' in red
print(crayons.red('red string', bold=True))

# print 'yellow string' in yellow
print(crayons.yellow('yellow string', bold=True))

# print 'magenta string' in magenta
print(crayons.magenta('magenta string', bold=True))

# print 'white string' in white
print(crayons.white('white string', bold=True))

print('{} {} {} {}'.format(crayons.red('red', bold=True),
                           crayons.blue('blue', bold=True),
                           crayons.yellow('yellow', bold=True),
예제 #11
0
    from backports.shutil_get_terminal_size import get_terminal_size
else:
    from shutil import get_terminal_size

#  ___  _       ___
# | . \<_> ___ | __>._ _  _ _
# |  _/| || . \| _> | ' || | |
# |_|  |_||  _/|___>|_|_||__/
#         |_|

# Enable shell completion.
click_completion.init()

# Disable colors, for the soulless.
if PIPENV_COLORBLIND:
    crayons.disable()

# Disable spinner, for cleaner build logs (the unworthy).
if PIPENV_NOSPIN:
    @contextlib.contextmanager
    def spinner():
        yield

# Disable warnings for Python 2.6.
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

project = Project()


def ensure_latest_pip():
    """Updates pip to the latest version."""
예제 #12
0
def start():

    if len(sys.argv) == 2 and sys.argv[1] == '-h':
        print(f'pytrancoder (ver {__version__})')
        print('usage: pytrancoder [OPTIONS]')
        print('  or   pytrancoder [OPTIONS] --from-file <filename>')
        print('  or   pytrancoder [OPTIONS] file ...')
        print('  or   pytrancoder -c <cluster> file... [--host <name>] -c <cluster> file...')
        print('No parameters indicates to process the default queue files using profile matching rules.')
        print(
            'The --from-file filename is a file containing a list of full paths to files for transcoding. ')
        print('OPTIONS:')
        print('  --host <name>  Name of a specific host in your cluster configuration to target, otherwise load-balanced')
        print('  -s         Process files sequentially even if configured for multiple concurrent jobs')
        print('  --dry-run  Run without actually transcoding or modifying anything, useful to test rules and profiles')
        print('  -v         Verbose output, helpful in debugging profiles and rules')
        print(
            '  -k         Keep source files after transcoding. If used, the transcoded file will have the same '
            'name and .tmp extension')
        print('  -y <file>  Full path to configuration file.  Default is ~/.transcode.yml')
        print('  -p         profile to use. If used with --from-file, applies to all listed media in <filename>')
        print('  -m         Add mixins to profile. Separate multiples with a comma')
        print('\n** PyPi Repo: https://pypi.org/project/pytranscoder-ffmpeg/')
        print('** Read the docs at https://pytranscoder.readthedocs.io/en/latest/')
        sys.exit(0)

    install_sigint_handler()
    files = list()
    profile = None
    mixins = None
    queue_path = None
    cluster = None
    configfile: Optional[ConfigFile] = None
    host_override = None
    if len(sys.argv) > 1:
        files = []
        arg = 1
        while arg < len(sys.argv):
            if sys.argv[arg] == '--from-file':          # load filenames to encode from given file
                queue_path = sys.argv[arg + 1]
                arg += 1
                tmpfiles = files_from_file(queue_path)
                if cluster is None:
                    files.extend([(f, profile) for f in tmpfiles])
                else:
                    files.extend([(f, cluster) for f in tmpfiles])
            elif sys.argv[arg] == '-p':                 # specific profile
                profile = sys.argv[arg + 1]
                arg += 1
            elif sys.argv[arg] == '-y':                 # specify yaml config file
                arg += 1
                configfile = ConfigFile(sys.argv[arg])
            elif sys.argv[arg] == '-k':                 # keep original
                pytranscoder.keep_source = True
            elif sys.argv[arg] == '--dry-run':
                pytranscoder.dry_run = True
            elif sys.argv[arg] == '--host':             # run all cluster encodes on specific host
                host_override = sys.argv[arg + 1]
                arg += 1
            elif sys.argv[arg] == '-v':                 # verbose
                pytranscoder.verbose = True
            elif sys.argv[arg] == '-c':                 # cluster
                cluster = sys.argv[arg + 1]
                arg += 1
            elif sys.argv[arg] == '-m':                 # mixins
                mixins = sys.argv[arg + 1].split(',')
                arg += 1
            else:
                if os.name == "nt":
                    expanded_files: List = glob.glob(sys.argv[arg])     # handle wildcards in Windows
                else:
                    expanded_files = [sys.argv[arg]]
                for f in expanded_files:
                    if cluster is None:
                        files.append((f, profile, mixins))
                    else:
                        files.append((f, cluster, profile, mixins))
            arg += 1

    if configfile is None:
        configfile = ConfigFile(DEFAULT_CONFIG)

    if not configfile.colorize:
        crayons.disable()
    else:
        crayons.enable()

    if len(files) == 0 and queue_path is None and configfile.default_queue_file is not None:
        #
        # load from list of files
        #
        tmpfiles = files_from_file(configfile.default_queue_file)
        queue_path = configfile.default_queue_file
        if cluster is None:
            files.extend([(f, profile, mixins) for f in tmpfiles])
        else:
            files.extend([(f, cluster, profile) for f in tmpfiles])

    if len(files) == 0:
        print(crayons.yellow(f'Nothing to do'))
        sys.exit(0)

    if cluster is not None:
        if host_override is not None:
            # disable all other hosts in-memory only - to force encodes to the designated host
            cluster_config = configfile.settings['clusters']
            for cluster in cluster_config.values():
                for name, this_config in cluster.items():
                    if name != host_override:
                        this_config['status'] = 'disabled'
        completed: List = manage_clusters(files, configfile)
        if len(completed) > 0:
            qpath = queue_path if queue_path is not None else configfile.default_queue_file
            pathlist = [p for p, _ in completed]
            cleanup_queuefile(qpath, set(pathlist))
            dump_stats(completed)
        sys.exit(0)

    host = LocalHost(configfile)
    host.enqueue_files(files)
    #
    # start all threads and wait for work to complete
    #
    host.start()
    if len(host.complete) > 0:
        completed_paths = [p for p, _ in host.complete]
        cleanup_queuefile(queue_path, set(completed_paths))
        dump_stats(host.complete)

    os.system("stty sane")
예제 #13
0
파일: color1.py 프로젝트: jpsura/MyCode
#!/usr/bin/env python3
import crayons

#print 'red string' in red
print(crayons.red('Red String'))

# red white an blue
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.disable() #disables color pack
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.
예제 #14
0
파일: cli.py 프로젝트: s0b0lev/pipenv
    from backports.shutil_get_terminal_size import get_terminal_size
else:
    from shutil import get_terminal_size

#  ___  _       ___
# | . \<_> ___ | __>._ _  _ _
# |  _/| || . \| _> | ' || | |
# |_|  |_||  _/|___>|_|_||__/
#         |_|

# Enable shell completion.
click_completion.init()

# Disable colors, for the soulless.
if PIPENV_COLORBLIND:
    crayons.disable()

# Disable spinner, for cleaner build logs (the unworthy).
if PIPENV_NOSPIN:
    @contextlib.contextmanager
    def spinner():
        yield

# Disable warnings for Python 2.6.
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

project = Project()


def ensure_latest_pip():
    """Updates pip to the latest version."""
예제 #15
0
def editorMain(fn):
    if options["2"] == "off":
        crayons.disable()
    with open(os.getcwd() + "/" + fn, mode="r") as filereadr:
        filecn = filereadr.read()
    linenum = 0
    filecn4 = filecn
    filecn4 = filecn4.split("\n")
    linenum = len(filecn4) + 1
    num = 0
    while True:
        linenum += 1
        os.system('printf "\e[48;5;241m \n"')
        os.system('printf "\e[8;20;46t"')
        clearScreen()
        print(genFEHdr(fn))
        filecn3 = filecn
        filecn3 = filecn3.split("\n")
        filecn2 = "1 "
        j = 0
        while j < len(filecn3):
            if str(filecn3[j]).startswith('^== '):
                filecn3[j] = str(crayons.black(filecn3[j]))
            filecn2 = filecn2 + filecn3[j] + "\n" + crayons.yellow(
                str(j + 2)) + " "
            j += 1
        filecn2 = filecn2.replace('prog', str(crayons.green("prog"))).replace(
            'print',
            str(crayons.blue("print"))).replace('eq', str(crayons.blue(
                "eq"))).replace('stop', str(crayons.yellow("stop"))).replace(
                    'debugOff', str(crayons.cyan("debugOff"))).replace(
                        'debugOn', str(crayons.cyan("debugOn"))).replace(
                            '$', str(crayons.magenta("$"))).replace(
                                '+', str(crayons.cyan("+"))).replace(
                                    '*', str(crayons.cyan("*"))).replace(
                                        '/', str(crayons.cyan("/"))).replace(
                                            '-',
                                            str(crayons.cyan("-"))).replace(
                                                'error',
                                                str(crayons.cyan("error"))
                                            ).replace(
                                                'err',
                                                str(crayons.cyan("error")))
        print("\n" + crayons.yellow(filecn2))
        c = input(crayons.yellow(str(linenum) + " "))  # Not fully implemented
        num += 1
        if num == 5:
            num = 0
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)
        addf = True
        if c == "****exit":
            os.system('printf "\e[48;5;0m \n"')
            addf = False
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)
            clearScreen()
            sys.exit()

        if c == "****save":
            addf = False
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)

        if c == "****run":
            addf = False
            if options["3"] == "on":
                with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                    filereadr.write(filecn)
                ResizeList(sys.argv, 2, fill_with=0)
                sys.argv[1] = fn
                frmain()
                input("++Press enter to return to editor++")

        if c == "****options":
            addf = False
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)
            clearScreen()
            print(
                crayons.red("░░░░ birchEditor ░ Edit Settings   ░░░░",
                            bold=True))
            print(
                crayons.red("Autosave:  " + options["1"] +
                            "                      1  !"))
            print(
                crayons.red("Color:     " + options["2"] +
                            "                      2 ok"))
            print(
                crayons.red("Run EDCMD: " + options["3"] +
                            "                      3 ok"))
            setting = input(
                crayons.yellow("change setting ['number,on/off']: "))
            setting = setting.split(',')
            options[setting[0]] = setting[1].lower()
            prefSaver()

        if c == "****jump":
            addf = False
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)
            clearScreen()
            print(
                crayons.red("░░░░ birchEditor ░ Jump to Line    ░░░░",
                            bold=True))
            setting = input(crayons.yellow("line number: "))
            print(
                crayons.cyan("""
Function Not available:
line text processing is in beta""",
                             bold=True))
            time.sleep(2)

        # Cursor Functions
        if c == "^[[A":
            addf = False
            linenum -= 1
        if c == "^[[B":
            addf = False
            linenum += 1
        if c == "^[[D":
            addf = False
            clearScreen()
            print(crayons.yelow("Saved code"))
            with open(os.getcwd() + "/" + fn, mode="w") as filereadr:
                filereadr.write(filecn)
            time.sleep(2)

        if c == "^[[C":
            clearScreen()
            d = input(crayons.yelow("Line Text [raw]: "))
            c = d

        if addf == True:
            filecn = filecn + "\n" + c