Python getopt.GetoptError() Examples

The following are code examples for showing how to use getopt.GetoptError(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: flasky   Author: RoseOu   File: cmdline.py    MIT License 6 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    # pylint: disable-msg=R0911,R0912,R0915

    usage = USAGE % ((args[0],) * 6)

    if sys.platform in ['win32', 'cygwin']:
        try:
            # Provide coloring under Windows, if possible
            import colorama
            colorama.init()
        except ImportError:
            pass

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
    except getopt.GetoptError, err:
        print >>sys.stderr, usage
        return 2 
Example 2
Project: zabbix   Author: xiaomatech   File: hdfs-collect.py    MIT License 6 votes vote down vote up
def main(argv):
    inputfile, outputfile = "", ""
    help_string = "Usage:\n./%s -i <input_file> -o <output_file>" % (argv[0])
    try:
        opts, args = getopt.getopt(argv[1:], "hi:o:", ["input", "output"])
    except getopt.GetoptError:
        print help_string
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print help_string
            sys.exit()
        elif opt in ("-i", "--input"):
            inputfile = arg
        elif opt in ("-o", "--output"):
            outputfile = arg

    result = scan(inputfile)
    try:
        with open(outputfile, "w") as f:
            f.write(json.dumps(result))
    except IOError:
        print "Error, cant read or write to file '%s'" % outputfile
        sys.exit(2) 
Example 3
Project: zabbix   Author: xiaomatech   File: getZookeeperInfo.py    MIT License 6 votes vote down vote up
def main(host, port, zkCommand, zkKey):

    try:
        options, args = getopt.getopt(
            sys.argv[1:], "h:p:c:k:",
            ["host=", "port=", "zkCommand=", "zkKey="])
        for name, value in options:
            if name in ('-h', '--host'):
                host = value
            if name in ('-p', '--port'):
                port = value
            if name in ('-c', '--zkCommand'):
                zkCommand = value
            if name in ('-k', '--zkKey'):
                zkKey = value
    except getopt.GetoptError, err:
        print str(err)
        Usage()
        sys.exit(1) 
Example 4
Project: Terminal-Pix   Author: Akatsuki06   File: util.py    MIT License 6 votes vote down vote up
def getArgs():
	try: 
		opts, args = getopt.getopt(sys.argv[1:],"f:h:w:",['help'])
	except getopt.GetoptError as e:
		print (str(e))
		print("Usage: %s " % sys.argv[0])
		sys.exit(2)
	file=''
	h=20
	w=20
	for o, a in opts:
		if o=='--help' :
			help()
		if o == '-f':
		   	file=a
		if o == '-h':
		    h=a
		if o =='-w':
			w=a


	return file,h,w 
Example 5
Project: openhatch   Author: campbe13   File: cmdline.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    # pylint: disable-msg=R0911,R0912,R0915

    usage = USAGE % ((args[0],) * 6)

    if sys.platform in ['win32', 'cygwin']:
        try:
            # Provide coloring under Windows, if possible
            import colorama
            colorama.init()
        except ImportError:
            pass

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
    except getopt.GetoptError, err:
        print >>sys.stderr, usage
        return 2 
Example 6
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: bitcointalk_sentiment_classifier.py    MIT License 6 votes vote down vote up
def main(argv):
    warnings.filterwarnings('ignore', category=DeprecationWarning)
    input_file = ''
    model_file = ''
    output_folder = ''
    output_posts = ''
    try:
        opts, args = getopt.getopt(argv, "hi:m:f:n:")
    except getopt.GetoptError:
        print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
            sys.exit()
        elif opt == '-i':
            input_file = arg
        elif opt == '-m':
            model_file = arg
        elif opt == '-f':
            output_folder = arg
        elif opt == '-n':
            output_posts = arg

    classify(input_file, model_file, output_folder, output_posts) 
Example 7
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: graph_builder.py    MIT License 6 votes vote down vote up
def main(argv):
    input_file = ''
    save_to = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:")
    except getopt.GetoptError:
        print('graph_builder.py -i <JSON inputfile> -o <output image>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('graph_builder.py -i <JSON inputfile> -o <output image>')
            sys.exit()
        elif opt == '-i':
            input_file = arg
        elif opt == '-o':
            save_to = arg

    build_graph(input_file,save_to) 
Example 8
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: graph_builder_month.py    MIT License 6 votes vote down vote up
def main(argv):
    input_file = ''
    save_to = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:")
    except getopt.GetoptError:
        print('graph_builder.py -i <JSON inputfile> -o <output image>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('graph_builder.py -i <JSON inputfile> -o <output image>')
            sys.exit()
        elif opt == '-i':
            input_file = arg
        elif opt == '-o':
            save_to = arg

    build_graph(input_file,save_to) 
Example 9
Project: selfieexpression   Author: andrewjtimmons   File: face.py    MIT License 6 votes vote down vote up
def parse_cmd_args(argv):
  """ Turns command line flags into variables """
  try:
      opts, args = getopt.getopt(argv,"hl:g:m:t:c:",["lat=", "lng=", "max_timestamp=", "min_timestamp=", "client_id="])
  except getopt.GetoptError:
    print 'face.py face.py "-l --lat, -g --lng, -m --max_timestamp, -c --client_id="'
    sys.exit(2)
  for opt, arg in opts:
    if opt == '-h':
       print 'face.py "-l --lat, -g --lng, -m --max_timestamp, -c --client_id="'
       sys.exit()
    elif opt in ("-l", "--lat"):
       api_call_lat = float(arg)
    elif opt in ("-g", "--lng"):
       api_call_lng = float(arg)
    elif opt in ("-m", "--max_timestamp"):
       max_timestamp = int(arg)
    elif opt in ("-t", "--min_timestamp"):
       min_timestamp = int(arg)
    elif opt in ("-c", "--client_id"):
       client_id = str(arg)
    else:
      assert False, "unhandled option"

  return api_call_lat, api_call_lng, max_timestamp, min_timestamp, client_id 
Example 10
Project: RTX   Author: RTXteam   File: PatchKG.py    MIT License 6 votes vote down vote up
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "had", ["add_has_phenotype_relations", "delete_duplicated_react_nodes"])
    except getopt.GetoptError:
        print("Wrong parameter")
        print("PatchKG.py -a <add_has_phenotype_relations> -d <delete_duplicated_react_nodes>")
        sys.exit(2)
    if len(opts) == 0:
        print("Need parameters")
        print("PatchKG.py -a <add_has_phenotype_relations> -d <delete_duplicated_react_nodes>")
    for opt, arg in opts:
        if opt == '-h':
            print("PatchKG.py -a <add_has_phenotype_relations> -d <delete_duplicated_react_nodes>")
            sys.exit()
        elif opt in ["-a", "--add_has_phenotype_relations"]:
            PatchKG.add_disease_has_phenotype_relations()
        elif opt in ["-d", "--delete_duplicated_react_nodes"]:
            PatchKG.delete_duplicated_react_nodes() 
Example 11
Project: TwitterClient   Author: brakmic   File: TwitterClient.py    MIT License 6 votes vote down vote up
def main(argv):
    try:
        init(wrap=True)
        opts, args = getopt.getopt(argv, "hc:d", ["help", "config="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h","--help"):
            usage()
            sys.exit()
        elif opt == '-d':
            global _debug
            _debug = True
        elif opt in ("-c","--config"):
            print('Loading config from file {0}'.format(arg))
            with codecs.open(arg,'r', encoding='utf-8') as config_file:
                _json = json.load(config_file)
                start_client(_json) 
Example 12
Project: tomodachi   Author: kalaspuff   File: __init__.py    MIT License 6 votes vote down vote up
def main(self, argv: List[str]) -> None:
        try:
            opts, args = getopt.getopt(argv, "hlvV ", ['help', 'log', 'version', 'version', 'dependency-versions'])
        except getopt.GetoptError:
            self.help_command()
        for opt, _ in opts:
            if opt in ['-h', '--help']:
                self.help_command()
            if opt in ['-v', '-V', '--version']:
                self.version_command()
            if opt in ['--dependency-versions']:
                self.dependency_versions_command()
        if len(args):
            if args[0] in ('run', 'start', 'go'):
                self.run_command(args[1:])
        self.help_command() 
Example 13
Project: labelmaker   Author: wundalous   File: v3labelmaker.py    GNU General Public License v3.0 6 votes vote down vote up
def main(argv):
    """
    Gets command-line arguments; sets name of JSON output file.
    """
    frmat = 'pretty'
    input_file = ''
    output_file = ''
    try:
        opts, args = getopt.getopt(argv,"hi:",["inputfile="])
    except getopt.GetoptError:
        print('v3labelmaker.py -i <name of input CSV file (without \'.csv\')>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('v3labelmaker.py -i <name of input CSV file (without \'.csv\')>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            input_file = arg + '.csv'
    output_file = arg + '.json'
    read_csv(input_file, output_file, frmat)
    return output_file 
Example 14
Project: RFXcomIdGenerator   Author: Sennevds   File: generateId.py    MIT License 6 votes vote down vote up
def main(argv):
   type = ''
   subtype = ''
   params = ''
   try:
      opts, args = getopt.getopt(argv,"ht:s:p:",["type=","subtype=", "params="])
   except getopt.GetoptError:
      print ('generateId.py -t <type> -s <subtype> -p <parameters>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ('generateId.py -t <type> -s <subtype> -p <parameters>')
         sys.exit()
      elif opt in ("-t", "--type"):
         type = arg
      elif opt in ("-s", "--subtype"):
         subtype = arg
      elif opt in ("-p", "--params"):
         params = arg
   list = params.split(",")

   generate_id(type,subtype, list) 
Example 15
Project: fuchsschwanz   Author: 20centaurifux   File: icbd.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_opts(argv):
    options, _ = getopt.getopt(argv, 'c:d:', ['config=', 'data-dir=', 'auto-respawn'])
    m = {"auto-respawn": False}

    for opt, arg in options:
        if opt in ('-c', '--config'):
            m["config"] = arg
        elif opt in ('-d', '--data-dir'):
            m["data_dir"] = arg
        elif opt in ('--auto-respawn',):
            m["auto-respawn"] = True

    if not m.get("config"):
        raise getopt.GetoptError("--config option is mandatory")

    if not m.get("data_dir"):
        raise getopt.GetoptError("--data-dir option is mandatory")

    return m 
Example 16
Project: unicorn-display   Author: actuino   File: client.py    MIT License 6 votes vote down vote up
def main(argv):
    global CONFIG_FILE_NAME
    try:
        opts, args = getopt.getopt(argv,"hc:",["help","config="])
    except getopt.GetoptError:
        print 'client.py -c <configfile> '
        sys.exit(2)
    for opt, arg in opts:
          if opt in ("-h", "--help"):
             print 'client.py -c <configfile> '
             sys.exit()
          elif opt in ("-c", "--config"):
             CONFIG_FILE_NAME = arg
    print 'Config file is "', CONFIG_FILE_NAME

    unicorndisplay.init(CONFIG_FILE_NAME) 
Example 17
Project: TAF   Author: couchbaselabs   File: ssh.py    Apache License 2.0 6 votes vote down vote up
def main():
    try:
        (opts, args) = getopt.getopt(sys.argv[1:], 'hi:p:', [])
        for o, a in opts:
            if o == "-h":
                usage()

        input = TestInput.TestInputParser.get_test_input(sys.argv)
        if not input.servers:
            usage(
                "ERROR: no servers specified. Please use the -i "
                "parameter.")
    except IndexError:
        usage()
    except getopt.GetoptError, error:
        usage("ERROR: " + str(error)) 
Example 18
Project: pyblish-win   Author: pyblish   File: findlinksto.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '')
        if len(args) < 2:
            raise getopt.GetoptError('not enough arguments', None)
    except getopt.GetoptError, msg:
        sys.stdout = sys.stderr
        print msg
        print 'usage: findlinksto pattern directory ...'
        sys.exit(2) 
Example 19
Project: pyblish-win   Author: pyblish   File: filecmp.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def demo():
    import sys
    import getopt
    options, args = getopt.getopt(sys.argv[1:], 'r')
    if len(args) != 2:
        raise getopt.GetoptError('need exactly two args', None)
    dd = dircmp(args[0], args[1])
    if ('-r', '') in options:
        dd.report_full_closure()
    else:
        dd.report() 
Example 20
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def assertError(self, *args, **kwargs):
        self.assertRaises(getopt.GetoptError, *args, **kwargs) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_issue4629(self):
        longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
        self.assertEqual(longopts, [('--help', '')])
        longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
        self.assertEqual(longopts, [('--help', 'x')])
        self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) 
Example 22
Project: NSAEQGRPFortinetVerify   Author: fnatalucci   File: check_fortinet_vuln.py    MIT License 5 votes vote down vote up
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hi:d", ["ip="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    if not opts:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print '### HELP? ma LOL ###'
            sys.exit()
        elif opt == "-i":
            ipToCheck = arg
         

    print '## Checking IP:',arg

    print '## Verify EGBL...'
    verifyConfig()
     
    print '## Check vulnerability...'
    verifyVuln(ipToCheck) 
Example 23
Project: pr-automerger-bot   Author: Repo3DS   File: brewman.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(argv):
	inputfile = ''
	dirname = ''
	try:
		opts, args = getopt.getopt(argv,"hi:d:",["help","file=","dir="])
	except getopt.GetoptError:
		print_help()
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			print_help()
			sys.exit()
		elif opt in ("-i", "--file"):
			inputfile = arg
		elif opt in ("-d", "--dir"):
			dirname = arg

	if inputfile and dirname:
		try:
			with open(inputfile) as f:
				config = yaml.load(f)
				app = BrewConfig(config, dirname)
				errorlist = app.validate()
				if errorlist:
					for error in errorlist:
						print(error)
				else:
					print("Validated successfully")
		except yaml.YAMLError as e:
			print("Error in configuration file:", e)
	else:
		print_help() 
Example 24
Project: dvrip   Author: alexshpilkin   File: discover.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(args: List[str]) -> None:
	try:
		opts, args = getopt(args, 'i:t:')
	except GetoptError:
		usage()
	if args:
		usage()

	interface = ''
	timeout   = 1.0
	for opt, arg in opts:
		if opt == '-i':
			try:
				interface = gethostbyname(arg)
			except OSError as e:
				osexit(e, EX_NOHOST)
		if opt == '-t':
			try:
				timeout = float(arg)
			except ValueError:
				usage()

	for result in DVRIPClient.discover(interface, timeout):
		print('{} {} {} {}/{} via {} port {} channels {}'
		      .format(result.serial, result.mac, result.name,
		              result.host, result.mask, result.router,
		              result.tcpport, result.channels)) 
Example 25
Project: dvrip   Author: alexshpilkin   File: log.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(host: str,
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	try:
		opts, args = getopt(args, 's:e:')
	except GetoptError:
		usage()
	if args:
		usage()

	start = EPOCH
	end = datetime.now()
	for opt, arg in opts:
		if opt == '-s':
			from dateparser import parse  # type: ignore
			start = parse(arg)
			if start is None:
				usage()
		if opt == '-e':
			from dateparser import parse  # type: ignore
			end = parse(arg)
			if end is None:
				usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)
	try:
		for entry in conn.log(start=start, end=end):
			print('{:>8} {} {:>12} {}'
			      .format(entry.number,
			              entry.time.isoformat(),
			              entry.type.name.lower(),
			              entry.data))
	finally:
		conn.logout() 
Example 26
Project: resticprofile   Author: creativeprojects   File: context.py    GNU General Public License v3.0 5 votes vote down vote up
def load_context_from_command_line(self, argv: list):
        try:
            short_options = self._get_short_options()
            long_options = self._get_long_options()
            self.opts, self.args = getopt(argv[1:], short_options, long_options)

        except GetoptError as err:
            console = Console()
            console.error("Error in the command arguments: " + err.msg)
            console.usage(argv[0])
            exit(2)

        for option, argument in self.opts:
            if option in self._get_possible_options_for('help'):
                Console().usage(argv[0])
                exit()

            elif option in self._get_possible_options_for('quiet'):
                self.quiet = True

            elif option in self._get_possible_options_for('verbose'):
                self.verbose = True

            elif option in self._get_possible_options_for('config'):
                self.configuration_file = argument

            elif option in self._get_possible_options_for('name'):
                self.profile_name = argument

            elif option in self._get_possible_options_for('no-ansi'):
                self.ansi = False

            else:
                assert False, "unhandled option" 
Example 27
Project: Adversarial_Video_Generation   Author: dyelax   File: process_data.py    MIT License 5 votes vote down vote up
def main():
    ##
    # Handle command line input
    ##

    num_clips = 5000000

    try:
        opts, _ = getopt.getopt(sys.argv[1:], 'n:t:c:oH',
                                ['num_clips=', 'train_dir=', 'clips_dir=', 'overwrite', 'help'])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-n', '--num_clips'):
            num_clips = int(arg)
        if opt in ('-t', '--train_dir'):
            c.TRAIN_DIR = c.get_dir(arg)
        if opt in ('-c', '--clips_dir'):
            c.TRAIN_DIR_CLIPS = c.get_dir(arg)
        if opt in ('-o', '--overwrite'):
            c.clear_dir(c.TRAIN_DIR_CLIPS)
        if opt in ('-H', '--help'):
            usage()
            sys.exit(2)

    # set train frame dimensions
    assert os.path.exists(c.TRAIN_DIR)
    c.FULL_HEIGHT, c.FULL_WIDTH = c.get_train_frame_dims()

    ##
    # Process data for training
    ##

    process_training_data(num_clips) 
Example 28
Project: pyWeatherGrab   Author: shazzner   File: pyWeatherGrab.py    GNU General Public License v2.0 5 votes vote down vote up
def parse_options():
    try:
        long_options = ['serial-port', 'baud', 'help', 'settings']
        opts, args = getopt.getopt(sys.argv[1:], "s:hb:i:", long_options)
    except getopt.GetoptError, e:
        print help()
        sys.exit(3)

    # Default options 
Example 29
Project: spy-ggp   Author: syllag   File: server.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def treat_opts(argv):
    try:
        opts, args = getopt.getopt(argv, 'hp:i:l::', ['help', 'lib_path=','lib_name=', 'port=', 'interface=', 'loglevel=', 'gdl_version='])

    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(-1)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif opt == '--lib_path':
            CONFIG['DLL_PATH']  = os.path.normpath(arg)
            print(CONFIG)
        elif opt == '--lib_name':
            CONFIG['DLL_NAME']  = arg
        elif opt == '--gdl_version':
            CONFIG['GDL_VERSION']  = arg
        elif opt in ('--port', '-p'):
            CONFIG['PORT']      = int(arg)
        elif opt in ('--interface', '-i'):
            CONFIG['IP']        = arg
        elif opt in ('loglevel=', '-l'):
            CONFIG['LOG_LEVEL'] = int(arg) 
Example 30
Project: steam_workshop_downloader   Author: Geam   File: workshop.py    MIT License 5 votes vote down vote up
def init(argv):
    """Read the args and return all variable
    Will return:
        - the number of error encounter
        - the absolute path of the output directory
        - an array of collection id given as args (in fact everything that is
            not a recognised arg
        - the absolute path of the save file
    Return int(error), string(output_dir), array(collections_id),
        string(save_file)
    """
    error = 0
    output_dir = os.getcwd()
    collections_id_list = []
    save_file = os.path.join(output_dir, "addons.lst")
    if len(argv) == 1 and not os.path.isfile(save_file):
        print("No save file found")
        usage(argv[0], 0)
    try:
        opts, args = getopt.getopt(argv[1:],"ho:")
    except getopt.GetoptError:
        usge(argv[0], 2)
    else:
        for opt, arg in opts:
            if opt == 'h':
                usge(argv[0], 0)
            elif opt == '-o':
                output_dir = os.path.abspath(arg)
                save_file = os.path.join(output_dir, "addons.lst")
        if not os.path.exists(output_dir):
            print(output_dir + ": path doesn't exist\nEnd of program")
            error += 1
        collections_id_list = argv[len(opts) * 2 + 1:]
    return error, output_dir, collections_id_list, save_file 
Example 31
Project: mininet_utils   Author: samueljero   File: traffic_source.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
	global client,port, fancy_names
	dns = []
	zero = 0
	tmdilation = 1
	try:                                
		opts, args = getopt.getopt(sys.argv[1:], "hc:p:d:z:f", ["help","client=", "port=","dns=", "zero=", "dilation="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	for opt,arg in opts:
		if opt in ("-c", "--client"):
			client=arg
		elif opt in ("-p", "--port"):
			port=int(arg)
		elif opt in ("-d", "--dns"):
			dfile=arg
			dns=parse_dns(dfile)
		elif opt in ("-z", "--zero"):
			zero=float(arg)
		elif opt in ("-f", "--dilation"):
			tmdilation=float(arg)
		elif opt in ("-h", "--help"):
			usage()
			sys.exit()
		else:
			print "Unknown Option"
			sys.exit()
	infiles=args
	if len(infiles)==0:
		print "Error, no matrices"
		sys.exit()
	flows, rtime=parse_mats(infiles, client,dns,tmdilation)
	flows=sort_flows(flows)
	do_test(flows,port, rtime, client,dns, zero) 
Example 32
Project: Repobot   Author: Desgard   File: cmdline.py    MIT License 5 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    usage = USAGE % ((args[0],) * 6)

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:vhVHgsx")
    except getopt.GetoptError:
        print(usage, file=sys.stderr)
        return 2

    try:
        return main_inner(popts, args, usage)
    except Exception:
        if '-v' in dict(popts):
            print(file=sys.stderr)
            print('*' * 65, file=sys.stderr)
            print('An unhandled exception occurred while highlighting.',
                  file=sys.stderr)
            print('Please report the whole traceback to the issue tracker at',
                  file=sys.stderr)
            print('<https://bitbucket.org/birkenfeld/pygments-main/issues>.',
                  file=sys.stderr)
            print('*' * 65, file=sys.stderr)
            print(file=sys.stderr)
            raise
        import traceback
        info = traceback.format_exception(*sys.exc_info())
        msg = info[-1].strip()
        if len(info) >= 3:
            # extract relevant file and position info
            msg += '\n   (f%s)' % info[-2].split('\n')[0].strip()[1:]
        print(file=sys.stderr)
        print('*** Error while highlighting:', file=sys.stderr)
        print(msg, file=sys.stderr)
        print('*** If this is a bug you want to report, please rerun with -v.',
              file=sys.stderr)
        return 1 
Example 33
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: bitcointalk_batch_classifier.py    MIT License 5 votes vote down vote up
def main(argv):
    input_folder = ''
    model_file = ''
    output_folder = ''
    announce_json = ''
    sentiment_json = ''
    output_posts = ''

    try:
        opts, args = getopt.getopt(argv, "hi:m:f:a:s:n:")
    except getopt.GetoptError:
        print('bitcointalk_batch_classifier.py -i <input folder> -m <model> -f <output folder> -a <announce JSON> -s <sentiment JSON> -n <number of output posts [number|fraction|all]>')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print('bitcointalk_batch_classifier.py -i <input folder> -m <model> -f <output folder> -a <announce JSON> -s <sentiment JSON> -n <number of output posts [number|fraction|all]>')
        elif opt == '-i':
            input_folder = arg
        elif opt == '-m':
            model_file = arg
        elif opt == '-f':
            output_folder = arg
        elif opt == '-a':
            announce_json = arg
        elif opt == '-s':
            sentiment_json = arg
        elif opt == '-n':
            output_posts = arg

    batch_classify(input_folder, model_file, output_folder, announce_json, sentiment_json, output_posts) 
Example 34
Project: razzy-spinner   Author: rafasashi   File: rid.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self, args):
    rid = RegressiveImageryDictionary()
    load_default_dict = True
    load_default_exc = True
    html_output = False
    title = "RID Analysis"

    try:
      optlist, args = getopt.getopt(sys.argv[1:], 'd:e:ht:',
                                    ['add-dict=', 'add-exc='])
      for (o, v) in optlist:
        if o == '-d':
          rid.load_dictionary_from_file(v)
          load_default_dict = False
        elif o == '-e':
          rid.load_exclusion_list_from_file(v)
          load_default_exc = False
        elif o == '--add-dict':
          rid.load_dictionary_from_file(v)
        elif o == '--add-exc':
          rid.load_exclusion_list_from_file(v)
        elif o == '-h':
          html_output = True
        elif o == '-t':
          title = v
        else:
          sys.stderr.write("%s: illegal option '%s'\n" % (args[0], o))
          self.usage(args)
    except getopt.GetoptError, e:
      sys.stderr.write("%s: %s\n" % (args[0], e.msg))
      self.usage(args)
      sys.exit(1) 
Example 35
Project: colorize   Author: BruXy   File: colorize.py    GNU General Public License v3.0 5 votes vote down vote up
def process_cli_options():
    global INPUT_FILES, VERBOSE, SUFFIX, TEST_RUN
    vprint("Input arguments:", sys.argv[1:])
    try:
        options, remainder = getopt.getopt(
            sys.argv[1:], 'vs:df:th',
            ['verbose', 'suffix=', 'delete', 'remote-folder=', 'test-run', 'help'])
    except getopt.GetoptError as err:
        print("Error: ", str(err))
        print_help()
        sys.exit(1)

    for opt, arg in options:
        if opt in ("-h", "--help"):
            print_help()
            sys.exit(0)
        elif opt in ("-v", "--verbose"):
            VERBOSE = True
            vprint("Verbose output enabled.")
        elif opt in ("-t", "--test-run"):
            TEST_RUN = True
            print("Test run enabled, nothing will be done.")
        elif opt in ("-s", "--suffix"):
            SUFFIX = arg
        else:
            assert False, "Unhandled option"

    if len(remainder) == 0:
        print_help()
        sys.exit(1)
    else:
        INPUT_FILES = list(remainder) 
Example 36
Project: rebel-framework   Author: reb311ion   File: sslstrip.py    GNU General Public License v3.0 5 votes vote down vote up
def parseOptions(argv):
    logFile      = 'sslstrip.log'
    logLevel     = logging.WARNING
    listenPort   = 10000
    spoofFavicon = False
    killSessions = False
    
    try:                                
        opts, args = getopt.getopt(argv, "hw:l:psafk", 
                                   ["help", "write=", "post", "ssl", "all", "listen=", 
                                    "favicon", "killsessions"])

        for opt, arg in opts:
            if opt in ("-h", "--help"):
                usage()
                sys.exit()
            elif opt in ("-w", "--write"):
                logFile = arg
            elif opt in ("-p", "--post"):
                logLevel = logging.WARNING
            elif opt in ("-s", "--ssl"):
                logLevel = logging.INFO
            elif opt in ("-a", "--all"):
                logLevel = logging.DEBUG
            elif opt in ("-l", "--listen"):
                listenPort = arg
            elif opt in ("-f", "--favicon"):
                spoofFavicon = True
            elif opt in ("-k", "--killsessions"):
                killSessions = True

        return (logFile, logLevel, listenPort, spoofFavicon, killSessions)
                    
    except getopt.GetoptError:           
        usage()                          
        sys.exit(2) 
Example 37
Project: robot-navigation   Author: ronaldahmed   File: exper.py    MIT License 5 votes vote down vote up
def main(self):
        try:
            opts,args = getopt.getopt(sys.argv[1:],'hgq',
                                            ['id=','size','info','pwd=','verbosity='])
        except getopt.GetoptError,err:
            print err
            sys.exit(self.USAGE) 
Example 38
Project: mdzz   Author: newbee-7   File: mdzz.py    MIT License 5 votes vote down vote up
def main():
    try:
        options, args = getopt.getopt(sys.argv[1:], ["help"])
    except getopt.GetoptError as e:
        pass

    match = re.findall(r'[\w.]+', " ".join(args).lower())
    words = "_".join(match)
    response = getResponse(words)
    if not response:
        return
    root = readXml(response)
    show(root) 
Example 39
Project: hlpr_speech   Author: HLP-R   File: speech_synthesizer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
  #print "\nCommand Line Args:"
  #print str(sys.argv[1:])

  #SpeechSynthesizer.setSynthesizer('espeak')
  
  #synthesizer = SpeechSynthesizer('Robin')
  synthesizer = SpeechSynthesizer()
  
  try:
    opts, args = getopt.getopt(sys.argv[1:], 'ho:', ["help", "say=", "output="])
  except getopt.GetoptError as err:
    # Print help information and exit
    print str(err)
    synthesizer.usage()
    sys.exit(2)

  message = None
  filename = None
  for o, a in opts:
    if o in ("-h", "--help"):
      synthesizer.usage()
      sys.exit()
    elif o in ("-s", "--say"):
      message = a
      synthesizer.say(message)
    elif o in ("-o", "--output"):
      filename = a
    else:
      assert False, "unhandled option"

  if(filename != None):
    synthesizer.outputToFile(message, filename)
  print("\n") 
Example 40
Project: redis-marshal   Author: mitjafelicijan   File: test_adjustments.py    MIT License 5 votes vote down vote up
def test_bad_param(self):
        import getopt
        self.assertRaises(getopt.GetoptError, self.parse, ['--no-host']) 
Example 41
Project: renthse   Author: warenix   File: provider.py    MIT License 5 votes vote down vote up
def main(argv):
    provider = None

    try:
        opts, args = getopt.getopt(argv, "hp:", ["provider="])
    except getopt.GetoptError:
        print 'provider.py -p <provider>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'provider.py -p <provider>'
            sys.exit()
        elif opt in ("-p", "--provider"):
            provider = arg

    if provider is not None:
        print 'provider is', provider

        if provider == '591':
            parser = Parser591()
            for i in range(1, 100):
                parser.fetch_page(i)
        elif provider == 'centanet':
            parser = ParserCentanet()
            for i in range(1, 300):
                parser.fetch_page(i)
        elif provider == 'hse28':
            parser = ParserHse28()
            parser.fetch_page() 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: filecmp.py    GNU General Public License v3.0 5 votes vote down vote up
def demo():
    import sys
    import getopt
    options, args = getopt.getopt(sys.argv[1:], 'r')
    if len(args) != 2:
        raise getopt.GetoptError('need exactly two args', None)
    dd = dircmp(args[0], args[1])
    if ('-r', '') in options:
        dd.report_full_closure()
    else:
        dd.report() 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_getopt.py    GNU General Public License v3.0 5 votes vote down vote up
def assertError(self, *args, **kwargs):
        self.assertRaises(getopt.GetoptError, *args, **kwargs) 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_getopt.py    GNU General Public License v3.0 5 votes vote down vote up
def test_issue4629(self):
        longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
        self.assertEqual(longopts, [('--help', '')])
        longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
        self.assertEqual(longopts, [('--help', 'x')])
        self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: findlinksto.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '')
        if len(args) < 2:
            raise getopt.GetoptError('not enough arguments', None)
    except getopt.GetoptError as msg:
        sys.stdout = sys.stderr
        print(msg)
        print('usage: findlinksto pattern directory ...')
        sys.exit(2)
    pat, dirs = args[0], args[1:]
    prog = re.compile(pat)
    for dirname in dirs:
        os.walk(dirname, visit, prog) 
Example 46
Project: grafana-csv-datasource   Author: SmartBlug   File: PythonServer.py    MIT License 5 votes vote down vote up
def main(argv):
	global path
	port = 3003
	debug = False
	addr = '0.0.0.0'
	try:
	  opts, args = getopt.getopt(argv,"hvp:f:a:",["port=","folder=","addr="])
	except getopt.GetoptError:
	  print 'PythonServer.py -p <port> -f <folder>'
	  sys.exit(2)
	for opt, arg in opts:
	  if opt == '-h':
	     print 'PythonServer.py -p <port> -f <folder>'
	     sys.exit()
	  elif opt in ("-a", "--addr"):
	     addr = arg
	  elif opt in ("-p", "--port"):
	     port = int(arg)
	  elif opt in ("-f", "--folder"):
	     path = arg
	  elif opt in ("-v"):
	     debug = True
	#print 'Port is ', port
	#print 'Folder is ', path
	print 'debug', debug
	
	app.run(host=addr, port=port, debug=debug) 
Example 47
Project: py3util   Author: DXCyber409   File: smali_split.py    Apache License 2.0 5 votes vote down vote up
def main(argv):
    smali_path = ''
    output_path = ''

    try:
        opts, args = getopt.getopt(argv,"ha:o:")
    except getopt.GetoptError:
        print_help()
        sys.exit(2)

    if (not opts):
        print_help()
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print_help()
            sys.exit()
        elif opt == '-a':
            smali_path = arg
        elif opt == '-o':
            output_path = arg
        
    if (not smali_path or not output_path):
        print_help()
        sys.exit()

    output_path = convert_path(output_path)
    smali_path = convert_path(smali_path)
    output_path = os.path.join(output_path, 'output')
    
    print('Start parsing entry path:' + str(smali_path))
    parse_dir(smali_path)
    print('Total split:' + str(cur_dex_num))
    split_smali_files(smali_path, output_path)
    compile_smali(output_path) 
Example 48
Project: py3util   Author: DXCyber409   File: smali_decompile.py    Apache License 2.0 5 votes vote down vote up
def main(argv):
    app_unzip_path = ''
    smali_output_path = ''
    mode = ''

    try:
        opts, args = getopt.getopt(argv,"hd:o:m:")
    except getopt.GetoptError:
        print_help()
        sys.exit(2)

    if (not opts):
        print_help()
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print_help()
            sys.exit()
        elif opt == '-d':
            app_unzip_path = arg
        elif opt == '-o':
            smali_output_path = arg
        elif opt == '-m' and arg in ('one', 'each'):
            mode = arg
        
    if (not app_unzip_path or not smali_output_path or not mode):
        print_help()
        sys.exit()
    
    dex_files = list_dexfile(app_unzip_path)
    print('dex file list:' + str(dex_files))
    if (not dex_files):
        print('dex file list empty!')
        sys.exit()
    
    if (mode == 'each'):
        smali_dex(dex_files, app_unzip_path, smali_output_path)
    elif (mode == 'one'):
        smali_dex_all_in_one(dex_files, app_unzip_path, smali_output_path) 
Example 49
Project: fuchsschwanz   Author: 20centaurifux   File: avatar_process.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_opts(argv):
    options, _ = getopt.getopt(argv, 'c:d:', ['config=', 'data-dir='])
    m = {}

    for opt, arg in options:
        if opt in ('-c', '--config'):
            m["config"] = arg

    if not m.get("config"):
        raise getopt.GetoptError("--config option is mandatory")

    return m 
Example 50
Project: fuchsschwanz   Author: 20centaurifux   File: mail_process.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_opts(argv):
    options, _ = getopt.getopt(argv, 'c:d:', ['config=', 'data-dir='])
    m = {}

    for opt, arg in options:
        if opt in ('-c', '--config'):
            m["config"] = arg

    if not m.get("config"):
        raise getopt.GetoptError("--config option is mandatory")

    return m