sys.argv.index

Here are the examples of the python api sys.argv.index taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

43 Examples 7

Example 1

Project: peppy
Source File: main.py
View license
def main():
    """Main entry point for editor.

    This is called from a script outside the package, parses the
    command line, and starts up a new wx.App.
    """

    try:
        index = sys.argv.index("-p")
        import cProfile
        cProfile.run('peppy.main.run()','profile.out')
    except ValueError:
        run()

Example 2

Project: Gnotero
Source File: gnotero_base.py
View license
	def cmdline_arg(self, arg):
		
		"""
		Returns a command line argument
		"""
		
		try:
			return sys.argv[sys.argv.index(arg) + 1]
		except:
			return None

Example 3

Project: python-hdf4
Source File: setup.py
View license
def _find_args(pat, env):
    val = os.environ.get(env, [])
    if val:
        val = val.split(os.pathsep)
    try:
        k = sys.argv.index(pat)
        val.extend(sys.argv[k+1].split(os.pathsep))
        del sys.argv[k]
        del sys.argv[k]
    except ValueError:
        pass
    return val

Example 4

View license
def main():

    # Check for the compile logs input flag and if found just compile the logs
    try:
        pos = sys.argv.index('--compile-logs')
    except: # Otherwise call the main argument handling function from the supporting file
        return cmt.util.processManyLakes.main(processing_function, LoggingClass,
                                              cmt.util.processManyLakes.get_image_collection_modis)

    # Compile flag found, just compile the logs.
    try:
        dataFolder = sys.argv[pos+1]
    except:
        print 'The data folder must follow "--compile-logs"'
        return 0
    return compileLakeResults(dataFolder)

Example 5

View license
def main():

    # Check for the compile logs input flag and if found just compile the logs
    try:
        pos = sys.argv.index('--compile-logs')
    except: # Otherwise call the main argument handling function from the supporting file
        return cmt.util.processManyLakes.main(processing_function, LoggingClass,
                                              cmt.util.processManyLakes.get_image_collection_modis)

    # Compile flag found, just compile the logs.
    try:
        dataFolder = sys.argv[pos+1]
    except:
        print 'The data folder must follow "--compile-logs"'
        return 0
    return compileLakeResults(dataFolder)

Example 6

Project: robothon
Source File: f2py2e.py
View license
def run_compile():
    """
    Do it all in one call!
    """
    import tempfile,os,shutil

    i = sys.argv.index('-c')
    del sys.argv[i]

    remove_build_dir = 0
    try: i = sys.argv.index('--build-dir')
    except ValueError: i=None
    if i is not None:
        build_dir = sys.argv[i+1]
        del sys.argv[i+1]
        del sys.argv[i]
    else:
        remove_build_dir = 1
        build_dir = os.path.join(tempfile.mktemp())

    sysinfo_flags = filter(re.compile(r'[-][-]link[-]').match,sys.argv[1:])
    sys.argv = filter(lambda a,flags=sysinfo_flags:a not in flags,sys.argv)
    if sysinfo_flags:
        sysinfo_flags = [f[7:] for f in sysinfo_flags]

    f2py_flags = filter(re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include').match,sys.argv[1:])
    sys.argv = filter(lambda a,flags=f2py_flags:a not in flags,sys.argv)
    f2py_flags2 = []
    fl = 0
    for a in sys.argv[1:]:
        if a in ['only:','skip:']:
            fl = 1
        elif a==':':
            fl = 0
        if fl or a==':':
            f2py_flags2.append(a)
    if f2py_flags2 and f2py_flags2[-1]!=':':
        f2py_flags2.append(':')
    f2py_flags.extend(f2py_flags2)

    sys.argv = filter(lambda a,flags=f2py_flags2:a not in flags,sys.argv)

    flib_flags = filter(re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)').match,sys.argv[1:])
    sys.argv = filter(lambda a,flags=flib_flags:a not in flags,sys.argv)
    fc_flags = filter(re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))').match,sys.argv[1:])
    sys.argv = filter(lambda a,flags=fc_flags:a not in flags,sys.argv)

    if 1:
        del_list = []
        for s in flib_flags:
            v = '--fcompiler='
            if s[:len(v)]==v:
                from numpy.distutils import fcompiler
                fcompiler.load_all_fcompiler_classes()
                allowed_keys = fcompiler.fcompiler_class.keys()
                nv = ov = s[len(v):].lower()
                if ov not in allowed_keys:
                    vmap = {} # XXX
                    try:
                        nv = vmap[ov]
                    except KeyError:
                        if ov not in vmap.values():
                            print 'Unknown vendor: "%s"' % (s[len(v):])
                    nv = ov
                i = flib_flags.index(s)
                flib_flags[i] = '--fcompiler=' + nv
                continue
        for s in del_list:
            i = flib_flags.index(s)
            del flib_flags[i]
        assert len(flib_flags)<=2,`flib_flags`
    setup_flags = filter(re.compile(r'[-][-](verbose)').match,sys.argv[1:])
    sys.argv = filter(lambda a,flags=setup_flags:a not in flags,sys.argv)
    if '--quiet' in f2py_flags:
        setup_flags.append('--quiet')

    modulename = 'untitled'
    sources = sys.argv[1:]
    if '-m' in sys.argv:
        i = sys.argv.index('-m')
        modulename = sys.argv[i+1]
        del sys.argv[i+1],sys.argv[i]
        sources = sys.argv[1:]
    else:
        from numpy.distutils.command.build_src import get_f2py_modulename
        pyf_files,sources = filter_files('','[.]pyf([.]src|)',sources)
        sources = pyf_files + sources
        for f in pyf_files:
            modulename = get_f2py_modulename(f)
            if modulename:
                break

    extra_objects, sources = filter_files('','[.](o|a|so)',sources)
    include_dirs, sources = filter_files('-I','',sources,remove_prefix=1)
    library_dirs, sources = filter_files('-L','',sources,remove_prefix=1)
    libraries, sources = filter_files('-l','',sources,remove_prefix=1)
    undef_macros, sources = filter_files('-U','',sources,remove_prefix=1)
    define_macros, sources = filter_files('-D','',sources,remove_prefix=1)
    using_numarray = 0
    using_numeric = 0
    for i in range(len(define_macros)):
        name_value = define_macros[i].split('=',1)
        if len(name_value)==1:
            name_value.append(None)
        if len(name_value)==2:
            define_macros[i] = tuple(name_value)
        else:
            print 'Invalid use of -D:',name_value

    from numpy.distutils.system_info import get_info

    num_include_dir = None
    num_info = {}
    #import numpy
    #n = 'numpy'
    #p = get_prefix(numpy)
    #from numpy.distutils.misc_util import get_numpy_include_dirs
    #num_info = {'include_dirs': get_numpy_include_dirs()}

    if num_info:
        include_dirs.extend(num_info.get('include_dirs',[]))

    from numpy.distutils.core import setup,Extension
    ext_args = {'name':modulename,'sources':sources,
                'include_dirs': include_dirs,
                'library_dirs': library_dirs,
                'libraries': libraries,
                'define_macros': define_macros,
                'undef_macros': undef_macros,
                'extra_objects': extra_objects,
                'f2py_options': f2py_flags,
                }

    if sysinfo_flags:
        from numpy.distutils.misc_util import dict_append
        for n in sysinfo_flags:
            i = get_info(n)
            if not i:
                outmess('No %s resources found in system'\
                        ' (try `f2py --help-link`)\n' % (`n`))
            dict_append(ext_args,**i)

    ext = Extension(**ext_args)
    sys.argv = [sys.argv[0]] + setup_flags
    sys.argv.extend(['build',
                     '--build-temp',build_dir,
                     '--build-base',build_dir,
                     '--build-platlib','.'])
    if fc_flags:
        sys.argv.extend(['config_fc']+fc_flags)
    if flib_flags:
        sys.argv.extend(['build_ext']+flib_flags)

    setup(ext_modules = [ext])

    if remove_build_dir and os.path.exists(build_dir):
        outmess('Removing build directory %s\n'%(build_dir))
        shutil.rmtree(build_dir)

Example 7

View license
def run_compile():
    """
    Do it all in one call!
    """
    import tempfile

    i = sys.argv.index('-c')
    del sys.argv[i]

    remove_build_dir = 0
    try:
        i = sys.argv.index('--build-dir')
    except ValueError:
        i = None
    if i is not None:
        build_dir = sys.argv[i + 1]
        del sys.argv[i + 1]
        del sys.argv[i]
    else:
        remove_build_dir = 1
        build_dir = tempfile.mkdtemp()

    _reg1 = re.compile(r'[-][-]link[-]')
    sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]
    if sysinfo_flags:
        sysinfo_flags = [f[7:] for f in sysinfo_flags]

    _reg2 = re.compile(
        r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include')
    f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]
    f2py_flags2 = []
    fl = 0
    for a in sys.argv[1:]:
        if a in ['only:', 'skip:']:
            fl = 1
        elif a == ':':
            fl = 0
        if fl or a == ':':
            f2py_flags2.append(a)
    if f2py_flags2 and f2py_flags2[-1] != ':':
        f2py_flags2.append(':')
    f2py_flags.extend(f2py_flags2)

    sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]
    _reg3 = re.compile(
        r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)')
    flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in flib_flags]
    _reg4 = re.compile(
        r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))')
    fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in fc_flags]

    if 1:
        del_list = []
        for s in flib_flags:
            v = '--fcompiler='
            if s[:len(v)] == v:
                from numpy.distutils import fcompiler
                fcompiler.load_all_fcompiler_classes()
                allowed_keys = list(fcompiler.fcompiler_class.keys())
                nv = ov = s[len(v):].lower()
                if ov not in allowed_keys:
                    vmap = {}  # XXX
                    try:
                        nv = vmap[ov]
                    except KeyError:
                        if ov not in vmap.values():
                            print('Unknown vendor: "%s"' % (s[len(v):]))
                    nv = ov
                i = flib_flags.index(s)
                flib_flags[i] = '--fcompiler=' + nv
                continue
        for s in del_list:
            i = flib_flags.index(s)
            del flib_flags[i]
        assert len(flib_flags) <= 2, repr(flib_flags)

    _reg5 = re.compile(r'[-][-](verbose)')
    setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in setup_flags]

    if '--quiet' in f2py_flags:
        setup_flags.append('--quiet')

    modulename = 'untitled'
    sources = sys.argv[1:]

    for optname in ['--include_paths', '--include-paths']:
        if optname in sys.argv:
            i = sys.argv.index(optname)
            f2py_flags.extend(sys.argv[i:i + 2])
            del sys.argv[i + 1], sys.argv[i]
            sources = sys.argv[1:]

    if '-m' in sys.argv:
        i = sys.argv.index('-m')
        modulename = sys.argv[i + 1]
        del sys.argv[i + 1], sys.argv[i]
        sources = sys.argv[1:]
    else:
        from numpy.distutils.command.build_src import get_f2py_modulename
        pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources)
        sources = pyf_files + sources
        for f in pyf_files:
            modulename = get_f2py_modulename(f)
            if modulename:
                break

    extra_objects, sources = filter_files('', '[.](o|a|so)', sources)
    include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1)
    library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)
    libraries, sources = filter_files('-l', '', sources, remove_prefix=1)
    undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)
    define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)
    for i in range(len(define_macros)):
        name_value = define_macros[i].split('=', 1)
        if len(name_value) == 1:
            name_value.append(None)
        if len(name_value) == 2:
            define_macros[i] = tuple(name_value)
        else:
            print('Invalid use of -D:', name_value)

    from numpy.distutils.system_info import get_info

    num_info = {}
    if num_info:
        include_dirs.extend(num_info.get('include_dirs', []))

    from numpy.distutils.core import setup, Extension
    ext_args = {'name': modulename, 'sources': sources,
                'include_dirs': include_dirs,
                'library_dirs': library_dirs,
                'libraries': libraries,
                'define_macros': define_macros,
                'undef_macros': undef_macros,
                'extra_objects': extra_objects,
                'f2py_options': f2py_flags,
                }

    if sysinfo_flags:
        from numpy.distutils.misc_util import dict_append
        for n in sysinfo_flags:
            i = get_info(n)
            if not i:
                outmess('No %s resources found in system'
                        ' (try `f2py --help-link`)\n' % (repr(n)))
            dict_append(ext_args, **i)

    ext = Extension(**ext_args)
    sys.argv = [sys.argv[0]] + setup_flags
    sys.argv.extend(['build',
                     '--build-temp', build_dir,
                     '--build-base', build_dir,
                     '--build-platlib', '.'])
    if fc_flags:
        sys.argv.extend(['config_fc'] + fc_flags)
    if flib_flags:
        sys.argv.extend(['build_ext'] + flib_flags)

    setup(ext_modules=[ext])

    if remove_build_dir and os.path.exists(build_dir):
        import shutil
        outmess('Removing build directory %s\n' % (build_dir))
        shutil.rmtree(build_dir)

Example 8

View license
def run_compile():
    """
    Do it all in one call!
    """
    import tempfile

    i = sys.argv.index('-c')
    del sys.argv[i]

    remove_build_dir = 0
    try:
        i = sys.argv.index('--build-dir')
    except ValueError:
        i = None
    if i is not None:
        build_dir = sys.argv[i + 1]
        del sys.argv[i + 1]
        del sys.argv[i]
    else:
        remove_build_dir = 1
        build_dir = tempfile.mkdtemp()

    _reg1 = re.compile(r'[-][-]link[-]')
    sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]
    if sysinfo_flags:
        sysinfo_flags = [f[7:] for f in sysinfo_flags]

    _reg2 = re.compile(
        r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include')
    f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]
    f2py_flags2 = []
    fl = 0
    for a in sys.argv[1:]:
        if a in ['only:', 'skip:']:
            fl = 1
        elif a == ':':
            fl = 0
        if fl or a == ':':
            f2py_flags2.append(a)
    if f2py_flags2 and f2py_flags2[-1] != ':':
        f2py_flags2.append(':')
    f2py_flags.extend(f2py_flags2)

    sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]
    _reg3 = re.compile(
        r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)')
    flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in flib_flags]
    _reg4 = re.compile(
        r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))')
    fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in fc_flags]

    if 1:
        del_list = []
        for s in flib_flags:
            v = '--fcompiler='
            if s[:len(v)] == v:
                from numpy.distutils import fcompiler
                fcompiler.load_all_fcompiler_classes()
                allowed_keys = list(fcompiler.fcompiler_class.keys())
                nv = ov = s[len(v):].lower()
                if ov not in allowed_keys:
                    vmap = {}  # XXX
                    try:
                        nv = vmap[ov]
                    except KeyError:
                        if ov not in vmap.values():
                            print('Unknown vendor: "%s"' % (s[len(v):]))
                    nv = ov
                i = flib_flags.index(s)
                flib_flags[i] = '--fcompiler=' + nv
                continue
        for s in del_list:
            i = flib_flags.index(s)
            del flib_flags[i]
        assert len(flib_flags) <= 2, repr(flib_flags)

    _reg5 = re.compile(r'[-][-](verbose)')
    setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
    sys.argv = [_m for _m in sys.argv if _m not in setup_flags]

    if '--quiet' in f2py_flags:
        setup_flags.append('--quiet')

    modulename = 'untitled'
    sources = sys.argv[1:]

    for optname in ['--include_paths', '--include-paths']:
        if optname in sys.argv:
            i = sys.argv.index(optname)
            f2py_flags.extend(sys.argv[i:i + 2])
            del sys.argv[i + 1], sys.argv[i]
            sources = sys.argv[1:]

    if '-m' in sys.argv:
        i = sys.argv.index('-m')
        modulename = sys.argv[i + 1]
        del sys.argv[i + 1], sys.argv[i]
        sources = sys.argv[1:]
    else:
        from numpy.distutils.command.build_src import get_f2py_modulename
        pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources)
        sources = pyf_files + sources
        for f in pyf_files:
            modulename = get_f2py_modulename(f)
            if modulename:
                break

    extra_objects, sources = filter_files('', '[.](o|a|so)', sources)
    include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1)
    library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)
    libraries, sources = filter_files('-l', '', sources, remove_prefix=1)
    undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)
    define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)
    for i in range(len(define_macros)):
        name_value = define_macros[i].split('=', 1)
        if len(name_value) == 1:
            name_value.append(None)
        if len(name_value) == 2:
            define_macros[i] = tuple(name_value)
        else:
            print('Invalid use of -D:', name_value)

    from numpy.distutils.system_info import get_info

    num_info = {}
    if num_info:
        include_dirs.extend(num_info.get('include_dirs', []))

    from numpy.distutils.core import setup, Extension
    ext_args = {'name': modulename, 'sources': sources,
                'include_dirs': include_dirs,
                'library_dirs': library_dirs,
                'libraries': libraries,
                'define_macros': define_macros,
                'undef_macros': undef_macros,
                'extra_objects': extra_objects,
                'f2py_options': f2py_flags,
                }

    if sysinfo_flags:
        from numpy.distutils.misc_util import dict_append
        for n in sysinfo_flags:
            i = get_info(n)
            if not i:
                outmess('No %s resources found in system'
                        ' (try `f2py --help-link`)\n' % (repr(n)))
            dict_append(ext_args, **i)

    ext = Extension(**ext_args)
    sys.argv = [sys.argv[0]] + setup_flags
    sys.argv.extend(['build',
                     '--build-temp', build_dir,
                     '--build-base', build_dir,
                     '--build-platlib', '.'])
    if fc_flags:
        sys.argv.extend(['config_fc'] + fc_flags)
    if flib_flags:
        sys.argv.extend(['build_ext'] + flib_flags)

    setup(ext_modules=[ext])

    if remove_build_dir and os.path.exists(build_dir):
        import shutil
        outmess('Removing build directory %s\n' % (build_dir))
        shutil.rmtree(build_dir)

Example 9

Project: buildfox
Source File: buildfox.py
View license
def main(*argv, **kwargs):
	# find out if user wants help about flags or something and slice all arguments after help
	arg_help = [sys.argv.index(v) for v in ["-h", "--help"] if v in sys.argv]
	arg_help = sys.argv[min(arg_help) + 1:] if arg_help else None
	if arg_help:
		lines = fox_core.split("\n")
		for arg in arg_help:
			# find stuff
			results = [index for index in range(0, len(lines)) if arg in lines[index]]
			# look behind/ahead
			results = [set([item for item in range(index - 1, index + 2) if item >= 0 and item < len(lines)]) for index in results]
			# merge context groups
			# so if we have [(0,1,2), (1,2,3)] we will have [(0,1,2,3)]
			merged_results = []
			while results:
				head = results[0]
				tail = results[1:]
				last_len = -1
				while len(head) > last_len:
					last_len = len(head)
					new_tail = []
					for rest in tail:
						if head.intersection(rest):
							head |= rest
						else:
							new_tail.append(rest)
					tail = new_tail
				merged_results.append(head)
				results = tail
			results = merged_results
			# merge strings
			results = "\n...\n".join(["\n".join([lines[item] for item in sorted(group)]) for group in results])
			# print results
			if results:
				print("results for %s:" % arg)
				print("...")
				print(results)
				print("...")
			else:
				print("no results for %s" % arg)
		exit(0)

	# parse arguments normally
	title = "buildfox ninja generator %s" % VERSION
	argsparser = argparse.ArgumentParser(description = title, add_help = False)
	argsparser.add_argument("-i", "--in", help = "input file", default = "build.fox")
	argsparser.add_argument("-o", "--out", help = "output file", default = "build.ninja")
	argsparser.add_argument("-w", "--workdir", help = "working directory")
	argsparser.add_argument("variables", metavar = "name=value", type = str, nargs = "*", help = "variables with values to setup", default = [])
	#argsparser.add_argument("-v", "--verbose", action = "store_true", help = "verbose output") # TODO
	argsparser.add_argument("--ide", help = "generate ide solution (vs, vs2012, vs2013, vs2015, xcode, make, qtcreator, cmake)", default = None, dest = "ide")
	argsparser.add_argument("--ide-prj", help = "ide project prefix", default = "build")
	argsparser.add_argument("--ide-env", help = "run provided command to set required environment before calling ninja from the ide, " +
		"use set NAME=VALUE form if you need to modify environment so it will work with all IDE's", default = None)
	argsparser.add_argument("--no-core", action = "store_false",
		help = "disable parsing fox core definitions", default = True, dest = "core")
	argsparser.add_argument("--no-env", action = "store_false",
		help = "disable environment discovery", default = True, dest = "env")
	argsparser.add_argument("-n", "--ninja-ide-gen", action = "store_true",
		help = "enables ninja ide generator mode (equal to --no-core --no-env)", default = False, dest = "ninja_ide_gen")
	# It won't be checked for real. Ninja will be run only if no arguments were passed.
	argsparser.add_argument("--just-generate", action = "store_true",
		help = "skips automatic ninja run", default = False, dest = "just_generate")
	argsparser.add_argument("--selftest", action = "store_true",
		help = "run self test", default = False, dest = "selftest")
	argsparser.add_argument("-v", "--ver", "--version", action = "version", version = title)
	argsparser.add_argument("-h", "--help", metavar = "REQUEST", type = str, nargs = "*",
		default = argparse.SUPPRESS, help = "look for request or show this help message and exit")
	args = vars(argsparser.parse_args())
	if "help" in args:
		argsparser.print_help()
		exit(0)

	if args.get("ninja_ide_gen"):
		args["core"] = False
		args["env"] = False
		args["in"] = "build.ninja" if args.get("in") == "build.fox" else args.get("in")
		args["out"] = ""

	if args.get("workdir"):
		os.chdir(args.get("workdir"))

	engine = Engine()

	if args.get("env"):
		env = discover()
		for name in sorted(env.keys()):
			engine.on_assign((name, env.get(name), "="))

	for var in args.get("variables"):
		parts = var.split("=")
		if len(parts) == 2:
			name, value = parts[0], parts[1]
			engine.on_assign((name, value, "="))
		else:
			raise SyntaxError("unknown argument '%s'. you should use name=value syntax to setup a variable" % var)

	if args.get("core"):
		engine.load_core(fox_core)

	if args.get("selftest"):
		fox_filename, ninja_filename, app_filename = selftest_setup()
		engine.load(fox_filename)
		engine.save(ninja_filename)
		result = not subprocess.call(["ninja", "-f", ninja_filename])
		if result:
			result = not subprocess.call(["./" + app_filename])
		if result:
			print("Selftest - ok")
			selftest_wipe()
		else:
			print("Selftest - failed")
			sys.exit(1)
	else:
		engine.load(args.get("in"))
		if len(args.get("out")):
			engine.save(args.get("out"))

		ide = args.get("ide")

		if ide in ["vs", "vs2012", "vs2013", "vs2015"]:
			if ide == "vs":
				ide = "vs" + engine.variables.get("toolset_msc_ver", "")
			gen_vs(
				engine.context.all_files,
				cxx_defines(engine.variables.get("defines", "")),
				cxx_includedirs(engine.variables.get("includedirs", "")),
				args.get("ide_prj"),
				ide,
				args.get("ide_env"))
		elif ide in ["xcode"]:
			gen_xcode(
				engine.context.all_files,
				cxx_includedirs(engine.variables.get("includedirs", "")),
				args.get("ide_prj"),
				args.get("in"),
				args.get("ide_env"),
				args.get("ninja_ide_gen"))
		elif ide in ["make"]:
			gen_make(
				args.get("in"),
				args.get("ide_env"),
				args.get("ninja_ide_gen"))
		elif ide in ["qtcreator"]:
			gen_qtcreator(
				engine.context.all_files,
				cxx_defines(engine.variables.get("defines", "")),
				cxx_includedirs(engine.variables.get("includedirs", "")),
				args.get("ide_prj"),
				args.get("in"),
				args.get("ide_env"),
				args.get("ninja_ide_gen"))
		elif ide in ["cmake"]:
			gen_cmake(
				engine.context.all_files,
				cxx_includedirs(engine.variables.get("includedirs", "")),
				args.get("ide_prj"),
				args.get("in"),
				args.get("ide_env"))
		elif ide is not None:
			raise ValueError("unknown ide '%s', available ide's : vs, vs2012, vs2013, vs2015, xcode, make, qtcreator, cmake" % ide)
	if len(sys.argv) == 1:
		sys.exit(subprocess.call("ninja" + (" -f " + args["out"] if len(args["out"]) else "")))

Example 10

Project: wal-e
Source File: backup.py
View license
def start_prefetches(seg, pd, how_many):
    from wal_e import pep3143daemon as daemon

    split = sys.argv.index('wal-fetch')
    if split < 0:
        return

    future = list(itertools.islice(seg.future_segment_stream(), how_many))

    for fs in future:
        if pd.is_running(fs) or pd.contains(fs):
            # Skip when it appears another pre-fetch is already
            # running or done.
            continue
        elif os.fork() == 0:
            pd.create(fs)
            # gpg sends garbage to stdout if it has to reopen stderr
            # so we just direct stderr to /dev/null instead
            with daemon.DaemonContext(stderr=open(os.devnull, 'w')):
                os.execvp(
                    sys.argv[0],
                    sys.argv[:split] + ['wal-prefetch'] + [pd.base, fs.name])

    return future

Example 11

Project: django-pytest
Source File: test_runner.py
View license
    def run_tests(self, test_labels, extra_tests=None):
        import pytest
        import sys

        if test_labels is None:
            print ('Not yet implemented: py.test is still not able to '
                   'discover the tests in all the INSTALLED_APPS as Django '
                   'requires.')
            exit(1)

        if extra_tests:
            print ('Not yet implemented: py.test is still not able to '
                   'run extra_tests as Django requires.')
            exit(1)

        pytest_args = []
        if self.failfast:
            pytest_args.append('--exitfirst')
        if self.verbosity == 0:
            pytest_args.append('--quiet')
        elif self.verbosity > 1:
            pytest_args.append('--verbose')

        # Remove arguments before (--). This separates Django command options
        # from py.test ones.
        try:
            pytest_args_index = sys.argv.index('--') + 1
            pytest_args.extend(sys.argv[pytest_args_index:])
        except ValueError:
            pass

        sys.exit(pytest.main(pytest_args))

Example 12

Project: cgstudiomap
Source File: session.py
View license
    def handle_command_line_options(self, to_handle):
        """Handle prescribed command line options and eat them.

        Anything before first occurrence of ``--`` on the command-line is taken
        into account and removed from ``sys.argv``.

        Help messages:

        If -h or --help is specified  and -- is not, the help for the wrapper
        will be printed, and the -h/--help option kept in sys.argv.

        If -h or --help is specified before --, the help for this wrapper will
        be printed and options after -- will be kept in sys.argv.

        if -h or --help is specified after --, it will be ignored at this
        stage, and kept in sys.argv (in most cases triggering help print for
        the wrapped script).
        """

        parser = OptionParser(
            usage="%(prog)s [OpenERP options] -- other arguments",
            description="This is a script rewrapped by OpenERP buildout "
                        "recipe to add OpenERP-related options on the command "
                        "line prior to other arguments.")

        if '-d' in to_handle:
            parser.add_option('-d', '--db-name',
                              help="Name of the database to work on. "
                              "If not specified, the database from "
                              "configuration files will be used")

        try:
            sep = sys.argv.index('--')
        except ValueError:
            if '-h' in sys.argv or '--help' in sys.argv:
                # in case of call myscript -h --, only the wrapper help
                # will be printed
                parser.epilog = ("Help message from the wrapped script, "
                                 "if any, will follow.")
                parser.print_help()
                print
                return
            our_argv = []
            sep = None
        else:
            our_argv = sys.argv[1:sep]

        options, args = parser.parse_args(our_argv)

        if sep is not None:
            del sys.argv[1:sep+1]

        if '-d' in to_handle:
            if options.db_name:
                logger.info("Opening database %r", options.db_name)
            else:
                logger.info("No database specified, using the one specified "
                            "in buildout configuration.")
            self.open(db=options.db_name)

Example 13

Project: ianitor
Source File: args_parser.py
View license
def parse_args():
    """
    Parse program arguments.

    This function ensures that argv arguments after '--' won't be parsed by
    `argparse` and will be returned as separate list.

    :return: (args, command) two-tuple
    """

    parser = get_parser()

    try:
        split_point = sys.argv.index('--')

    except ValueError:
        if "--help" in sys.argv or "-h" in sys.argv or len(sys.argv) == 1:
            parser.print_help()
            exit(0)
        else:
            parser.print_usage()
            print(parser.prog, ": error: command missing")
            exit(1)

    else:
        argv = sys.argv[1:split_point]
        invocation = sys.argv[split_point + 1:]

        args = parser.parse_args(argv)

        # set default heartbeat to ttl / 10. if not specified
        if not args.heartbeat:
            args.heartbeat = args.ttl / 10.
            logger.debug(
                "heartbeat not specified, setting to %s" % args.heartbeat
            )

        return args, invocation

Example 14

Project: dit
Source File: setup.py
View license
def main():
    ## Probably, we don't need this anymore?
    hack_distutils()

    # Handle optional extensions.
    opt = {}
    for name, option in [('Cython', 'nocython')]:
        lname = name.lower()

        # Determine if the Python module exists
        opt[lname] = check_opt(name)

        if not opt[lname]:
            continue
        else:
            # Disable installation of extensions, if user requested.
            try:
                idx = sys.argv.index("--{0}".format(option))
            except ValueError:
                pass
            else:
                opt[lname] = False
                del sys.argv[idx]

    cmdclass = {'install_data': my_install_data}

    cython_modules = []
    if opt['cython']:
        import Cython.Distutils
        try:
            import numpy as np
        except ImportError:
            msg = "Please install NumPy first."
            print(msg)
            raise

        cmdclass['build_ext'] = Cython.Distutils.build_ext

        cython_modules = []

        close = Extension(
            "dit.math._close",
            ["dit/math/_close.pyx"]
        )

        pycounts = Extension(
            "dit.inference.pycounts",
            ["dit/inference/pycounts.pyx", "dit/inference/counts.c"],
            include_dirs=[np.get_include()],
            libraries=['m'],
            extra_compile_args=['-std=c99'],
        )

        samplediscrete = Extension(
            "dit.math._samplediscrete",
            ["dit/math/_samplediscrete.pyx"],
            include_dirs=[np.get_include()]
        )

        # Active Cython modules
        cython_modules = [
            close,
            pycounts,
            samplediscrete,
        ]

    other_modules = []

    ext_modules = cython_modules + \
                  other_modules

    data_files = ()

    with open('requirements.txt') as reqs:
        install_requires = reqs.read().splitlines()

    if sys.version_info[:2] <= (3, 3):
        with open('requirements_lt33.txt') as reqs:
            install_requires.extend(reqs.read().splitlines())

    packages = [
        'dit',
        'dit.algorithms',
        'dit.divergences',
        'dit.example_dists',
        'dit.inference',
        'dit.math',
        'dit.multivariate',
        'dit.other',
        'dit.profiles',
        'dit.shannon',
        'dit.utils',
    ]

    # Tests
    # This includes for bdist only. sdist uses MANIFEST.in
    package_data = dict(zip(packages, [['tests/*.py']]*len(packages)))

    kwds = {
        'name':                 "dit",
        'version':              version,
        'url':                  "http://dit.io",

        'packages':             packages,
        'package_data':         package_data,
        'provides':             ['dit'],
        'install_requires':     install_requires,
        'ext_modules':          ext_modules,
        'cmdclass':             cmdclass,
        'data_files':           data_files,
        'include_package_data': True,

        'author':               "Humans",
        'author_email':         "[email protected]",
        'description':          "Python package for information theory.",
        'long_description':     open('README.rst').read(),
        'license':              "BSD",
    }

    # Automatic dependency resolution is supported only by setuptools.
    if not has_setuptools:
        del kwds['install_requires']

    setup(**kwds)

Example 15

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "WTF does %s mean?" %mode
	print "    Check available modes in the help."
	print "    But I know you are a lazy fuck, so here's the help for you..."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 16

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "WTF does %s mean?" %mode
	print "    Check available modes in the help."
	print "    But I know you are a lazy fuck, so here's the help for you..."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 17

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Unknown mode %s." %mode
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 18

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Unknown mode %s." %mode
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 19

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		  '--max-aps','--rssi','--airodump-time','--tiempo','--canal','--output','--modo']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--modo':
      USE_MODES = True
      modo = argv[argv.index(arg)+1]
      if modo == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif modo == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif modo == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERTA + "No se reconocio el modo %s." %modo
	print "    Revise la ayuda para ver que modos disponibles hay."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 20

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		  '--max-aps','--rssi','--airodump-time','--tiempo','--canal','--output','--modo']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--modo':
      USE_MODES = True
      modo = argv[argv.index(arg)+1]
      if modo == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif modo == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif modo == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERTA + "No se reconocio el modo %s." %modo
	print "    Revise la ayuda para ver que modos disponibles hay."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 21

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 22

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 23

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 24

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 25

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 26

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 27

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 28

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

Example 29

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Do you even mode bro?"
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 30

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Do you even mode bro?"
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 31

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Unknown mode %s." %mode
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 32

View license
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		 '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--mode':
      USE_MODES = True
      mode = argv[argv.index(arg)+1]
      if mode == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif mode == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif mode == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERT + "Unknown mode %s." %mode
	print "    Check available modes in the help."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 33

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		  '--max-aps','--rssi','--airodump-time','--tiempo','--canal','--output','--modo']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--modo':
      USE_MODES = True
      modo = argv[argv.index(arg)+1]
      if modo == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif modo == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif modo == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERTA + "No se reconocio el modo %s." %modo
	print "    Revise la ayuda para ver que modos disponibles hay."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 34

View license
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_PIXIEWPS
  global AIRODUMP_TIME
  global REAVER_TIME
  global CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  global BLACKLIST
  global RSSI
  global MAX_APS
  global USE_MODES
  H = ['-h','--help']
  flags = ['-p','-P','-f','-q','-F','-A']
  binary_flags = ['-a','-t','-c','-o','-s','-m','-M',
		  '--max-aps','--rssi','--airodump-time','--tiempo','--canal','--output','--modo']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-m' or arg == '--modo':
      USE_MODES = True
      modo = argv[argv.index(arg)+1]
      if modo == 'WALK':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 4
	REAVER_TIME = 8
	GET_PASSWORD = True
	FOREVER = True
	MAX_APS = 2
      elif modo == 'DRIVE':
	USE_PIXIEWPS = True
	REAVER_TIME = 10
	FOREVER = True
	MAX_APS = 1
      elif modo == 'STATIC':
	USE_PIXIEWPS = True
	AIRODUMP_TIME = 5
	REAVER_TIME = 10
	GET_PASSWORD = True
	PROMPT_APS = True
	OVERRIDE = False
      else:
	print ALERTA + "No se reconocio el modo %s." %modo
	print "    Revise la ayuda para ver que modos disponibles hay."
	help()
    elif arg == '-M' or arg == '--max-aps':
      try:
	MAX_APS == int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-s' or arg == '--rssi':
      try:
	RSSI = int(argv[argv.index(arg)+1])
	if RSSI < -100 or RSSI > 0: help()
      except ValueError:
	help()
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-a' or arg == '--airodump-time':
      try:
	AIRODUMP_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
	if REAVER_TIME <= 0: help()
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	CHANNEL = int(argv[argv.index(arg)+1])
	if CHANNEL <= 0 or CHANNEL >= 15: help()
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      try:
	m = argv[argv.index(arg)+1]
	if m not in flags:
	  if m not in binary_flags: OUTPUT_FILE = m
      except IndexError:
	pass
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-A' or arg == '--again':
      OVERRIDE = False
      BLACKLIST = False
    else:
      help()
    if CHANNEL != '':
      AIRODUMP_TIME = 1

Example 35

Project: Incor
Source File: main.py
View license
def main():
    """
    The entry function for the command 'incor' in terminal
    """

    template = 'template'
    input_file = None
    compilers = ['g++', 'gcc', 'python']
    flag_list = ['-t', '-i', '-cpp', '-c', '-py']

    def get_arg(arg, default=None):
        try:
            global ind
            ind = sys.argv.index(arg)
            value = sys.argv[ind + 1]
            if value not in flag_list:
                sys.argv = sys.argv[:ind] + sys.argv[ind + 2:]
                return True, value
            else:
                sys.argv = sys.argv[:ind] + sys.argv[ind + 1:]
                return True, default
        except ValueError:
            return False, default
        except IndexError:
            sys.argv = sys.argv[:ind]
            return True, default

    present, template = get_arg('-t', template)
    present, input_name = get_arg('-i')
    if input_name is None and present:
        input_name = 'input.txt'
    present, compilers[0] = get_arg('-cpp', compilers[0])
    present, compilers[1] = get_arg('-c', compilers[1])
    present, compilers[2] = get_arg('-py', compilers[2])

    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    if path == '--version':
        print('incor v' + incor.__version__)
        return
    elif path == '-h' or path == '--help':
        print("""incor can be configured for a run using these options -

    -i   : To specify the input file name for the to be compiled program
    (with extension).
    -t   : To specify the name of template file(without extension).
    -c   : To specify the C compiler to be used.
    -cpp : To specify the C++ compiler to be used.
    -py  : To specify the python interpreter to be used.

        """)
        return
    else:
        sys.argv = sys.argv[1:]
        path = " ".join(sys.argv) if len(sys.argv) > 0 else '.'
        os.chdir(path)
        path = '.'

    if input_name is not None:
        for root, dirs, files in os.walk(path):
            if input_name in files:
                input_file = os.path.join(root, input_name)
                break
        if input_file is None:
            print(input_name + ' not found')
    eventhandler = EventHandler(path, compilers)
    eventhandler.parentPid = os.getpid()  # parent process pid
    eventhandler.TemplateName = template

    observer = Observer()
    observer.schedule(eventhandler, path, recursive=True)
    observer.start()
    try:
        while True:
            if eventhandler.newCmd:

                # stores the status of the cmd
                eventhandler.newCmd = False

                # flushes the keystrokes of the previously terminated program
                sys.stdout.flush()
                sys.stdout.flush()
                tcflush(sys.stdin, TCIOFLUSH)

                start_time = time.time()
                # creates a child process that executes the final command
                if input_file is not None:
                    input_fd = open(input_file, 'r')
                    call(eventhandler.cmd, shell=True, stdin=input_fd)
                    input_fd.close()
                else:
                    call(eventhandler.cmd, shell=True)
                print('\n---------------------------------------------------')
                print('Program execution terminated in %s seconds.' %
                      (time.time() - start_time))
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

Example 36

Project: shellpy
Source File: shellpy.py
View license
def main(python_version):
    custom_usage = '''%(prog)s [SHELLPY ARGS] file [SCRIPT ARGS]

For arguments help use:
    %(prog)s --help
    '''
    custom_epilog = '''github : github.com/lamerman/shellpy'''

    def is_shellpy_file(fil):
        if not re.match('.+\.spy$', fil):
            parser.error('Shellpy can only run *.spy files')
        return fil

    parser = ArgumentParser(description='A tool for convenient shell scripting in python',
                            usage=custom_usage, epilog=custom_epilog)
    parser.add_argument('file', help='path to spy file', type=is_shellpy_file)
    parser.add_argument('-v', '--verbose', help='increase output verbosity. Always print the command being executed',
                        action="store_true")
    parser.add_argument('-vv', help='even bigger output verbosity. All stdout and stderr of executed commands is '
                                    'printed', action="store_true")

    shellpy_args, unknown_args = parser.parse_known_args()

    if shellpy_args.verbose or shellpy_args.vv:
        config.PRINT_ALL_COMMANDS = True

    if shellpy_args.vv:
        config.PRINT_STDOUT_ALWAYS = True
        config.PRINT_STDERR_ALWAYS = True

    filename = shellpy_args.file
    filename_index = sys.argv.index(filename)
    # remove script arguments given before script name
    # comment out if want to keep them
    script_args = [x for x in unknown_args if x not in sys.argv[:filename_index]]

    processed_file = preprocess_file(filename, is_root_script=True, python_version=python_version)

    # include directory of the script to pythonpath
    new_env = os.environ.copy()
    new_env['PYTHONPATH'] = new_env.get("PYTHONPATH", '') + os.pathsep + os.path.dirname(filename)
    new_env[SHELLPY_PARAMS] = config.dumps()

    retcode = subprocess.call(processed_file + ' ' + ' '.join(script_args), shell=True, env=new_env)
    exit(retcode)

Example 37

Project: shellpy
Source File: shellpy.py
View license
def main(python_version):
    custom_usage = '''%(prog)s [SHELLPY ARGS] file [SCRIPT ARGS]

For arguments help use:
    %(prog)s --help
    '''
    custom_epilog = '''github : github.com/lamerman/shellpy'''

    def is_shellpy_file(fil):
        if not re.match('.+\.spy$', fil):
            parser.error('Shellpy can only run *.spy files')
        return fil

    parser = ArgumentParser(description='A tool for convenient shell scripting in python',
                            usage=custom_usage, epilog=custom_epilog)
    parser.add_argument('file', help='path to spy file', type=is_shellpy_file)
    parser.add_argument('-v', '--verbose', help='increase output verbosity. Always print the command being executed',
                        action="store_true")
    parser.add_argument('-vv', help='even bigger output verbosity. All stdout and stderr of executed commands is '
                                    'printed', action="store_true")

    shellpy_args, unknown_args = parser.parse_known_args()

    if shellpy_args.verbose or shellpy_args.vv:
        config.PRINT_ALL_COMMANDS = True

    if shellpy_args.vv:
        config.PRINT_STDOUT_ALWAYS = True
        config.PRINT_STDERR_ALWAYS = True

    filename = shellpy_args.file
    filename_index = sys.argv.index(filename)
    # remove script arguments given before script name
    # comment out if want to keep them
    script_args = [x for x in unknown_args if x not in sys.argv[:filename_index]]

    processed_file = preprocess_file(filename, is_root_script=True, python_version=python_version)

    # include directory of the script to pythonpath
    new_env = os.environ.copy()
    new_env['PYTHONPATH'] = new_env.get("PYTHONPATH", '') + os.pathsep + os.path.dirname(filename)
    new_env[SHELLPY_PARAMS] = config.dumps()

    retcode = subprocess.call(processed_file + ' ' + ' '.join(script_args), shell=True, env=new_env)
    exit(retcode)

Example 38

Project: anybox.recipe.odoo
Source File: session.py
View license
    def handle_command_line_options(self, to_handle):
        """Handle prescribed command line options and eat them.

        Anything before first occurrence of ``--`` on the command-line is taken
        into account and removed from ``sys.argv``.

        Help messages:

        If -h or --help is specified  and -- is not, the help for the wrapper
        will be printed, and the -h/--help option kept in sys.argv.

        If -h or --help is specified before --, the help for this wrapper will
        be printed and options after -- will be kept in sys.argv.

        if -h or --help is specified after --, it will be ignored at this
        stage, and kept in sys.argv (in most cases triggering help print for
        the wrapped script).
        """

        parser = OptionParser(
            usage="%(prog)s [Odoo options] -- other arguments",
            description="This is a script rewrapped by Odoo buildout "
                        "recipe to add Odoo-related options on the command "
                        "line prior to other arguments.")

        if '-d' in to_handle:
            parser.add_option('-d', '--db-name',
                              help="Name of the database to work on. "
                              "If not specified, the database from "
                              "configuration files will be used")

        try:
            sep = sys.argv.index('--')
        except ValueError:
            if '-h' in sys.argv or '--help' in sys.argv:
                # in case of call myscript -h --, only the wrapper help
                # will be printed
                parser.epilog = ("Help message from the wrapped script, "
                                 "if any, will follow.")
                parser.print_help()
                print
                return
            our_argv = []
            sep = None
        else:
            our_argv = sys.argv[1:sep]

        options, args = parser.parse_args(our_argv)

        if sep is not None:
            del sys.argv[1:sep+1]

        if '-d' in to_handle:
            if options.db_name:
                logger.info("Opening database %r", options.db_name)
            else:
                logger.info("No database specified, using the one specified "
                            "in buildout configuration.")
            self.open(db=options.db_name)

Example 39

Project: anybox.recipe.odoo
Source File: session.py
View license
    def handle_command_line_options(self, to_handle):
        """Handle prescribed command line options and eat them.

        Anything before first occurrence of ``--`` on the command-line is taken
        into account and removed from ``sys.argv``.

        Help messages:

        If -h or --help is specified  and -- is not, the help for the wrapper
        will be printed, and the -h/--help option kept in sys.argv.

        If -h or --help is specified before --, the help for this wrapper will
        be printed and options after -- will be kept in sys.argv.

        if -h or --help is specified after --, it will be ignored at this
        stage, and kept in sys.argv (in most cases triggering help print for
        the wrapped script).
        """

        parser = OptionParser(
            usage="%(prog)s [Odoo options] -- other arguments",
            description="This is a script rewrapped by Odoo buildout "
                        "recipe to add Odoo-related options on the command "
                        "line prior to other arguments.")

        if '-d' in to_handle:
            parser.add_option('-d', '--db-name',
                              help="Name of the database to work on. "
                              "If not specified, the database from "
                              "configuration files will be used")

        try:
            sep = sys.argv.index('--')
        except ValueError:
            if '-h' in sys.argv or '--help' in sys.argv:
                # in case of call myscript -h --, only the wrapper help
                # will be printed
                parser.epilog = ("Help message from the wrapped script, "
                                 "if any, will follow.")
                parser.print_help()
                print
                return
            our_argv = []
            sep = None
        else:
            our_argv = sys.argv[1:sep]

        options, args = parser.parse_args(our_argv)

        if sep is not None:
            del sys.argv[1:sep+1]

        if '-d' in to_handle:
            if options.db_name:
                logger.info("Opening database %r", options.db_name)
            else:
                logger.info("No database specified, using the one specified "
                            "in buildout configuration.")
            self.open(db=options.db_name)

Example 40

Project: Flask-SocketIO
Source File: cli.py
View license
@click.command()
@click.option('--host', '-h', default='127.0.0.1',
              help='The interface to bind to.')
@click.option('--port', '-p', default=5000,
              help='The port to bind to.')
@click.option('--reload/--no-reload', default=None,
              help='Enable or disable the reloader.  By default the reloader '
              'is active if debug is enabled.')
@click.option('--debugger/--no-debugger', default=None,
              help='Enable or disable the debugger.  By default the debugger '
              'is active if debug is enabled.')
@click.option('--eager-loading/--lazy-loader', default=None,
              help='Enable or disable eager loading.  By default eager '
              'loading is enabled if the reloader is disabled.')
@pass_script_info
def run(info, host, port, reload, debugger, eager_loading):
    """Runs a local development server for the Flask-SocketIO application.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask-SocketIO app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    def run_server():
        app = info.load_app()
        if 'socketio' not in app.extensions:
            # flask-socketio is installed, but it isn't in this application
            # so we invoke Flask's original run command
            run_index = sys.argv.index('run')
            sys.argv = sys.argv[run_index:]
            return run_command()
        socketio = app.extensions['socketio']
        socketio.run(app, host=host, port=port, debug=debugger,
                     use_reloader=False, log_output=debugger)

    if reload:
        from werkzeug.serving import run_with_reloader
        run_with_reloader(run_server)
    else:
        run_server()

Example 41

Project: Flask-SocketIO
Source File: cli.py
View license
@click.command()
@click.option('--host', '-h', default='127.0.0.1',
              help='The interface to bind to.')
@click.option('--port', '-p', default=5000,
              help='The port to bind to.')
@click.option('--reload/--no-reload', default=None,
              help='Enable or disable the reloader.  By default the reloader '
              'is active if debug is enabled.')
@click.option('--debugger/--no-debugger', default=None,
              help='Enable or disable the debugger.  By default the debugger '
              'is active if debug is enabled.')
@click.option('--eager-loading/--lazy-loader', default=None,
              help='Enable or disable eager loading.  By default eager '
              'loading is enabled if the reloader is disabled.')
@pass_script_info
def run(info, host, port, reload, debugger, eager_loading):
    """Runs a local development server for the Flask-SocketIO application.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask-SocketIO app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    def run_server():
        app = info.load_app()
        if 'socketio' not in app.extensions:
            # flask-socketio is installed, but it isn't in this application
            # so we invoke Flask's original run command
            run_index = sys.argv.index('run')
            sys.argv = sys.argv[run_index:]
            return run_command()
        socketio = app.extensions['socketio']
        socketio.run(app, host=host, port=port, debug=debugger,
                     use_reloader=False, log_output=debugger)

    if reload:
        from werkzeug.serving import run_with_reloader
        run_with_reloader(run_server)
    else:
        run_server()

Example 42

Project: quickopen
Source File: prelaunch_client.py
View license
def remove_prelaunch_from_sys_argv():
  index_of_prelaunch = sys.argv.index('prelaunch')
  assert index_of_prelaunch != -1
  del sys.argv[index_of_prelaunch]

Example 43

Project: quickopen
Source File: prelaunch_client.py
View license
def remove_prelaunch_from_sys_argv():
  index_of_prelaunch = sys.argv.index('prelaunch')
  assert index_of_prelaunch != -1
  del sys.argv[index_of_prelaunch]