Python sys.argv() Examples

The following are 50 code examples for showing how to use sys.argv(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: MIT-CS-lectures   Author: William-Python-King   File: stdio.py View Source Project 6 votes vote down vote up
def _main():
    """
    For testing. The command-line argument should be the name of the
    function that should be called.
    """

    map = {
        'readInt':    readInt,    'readAllInts':    readAllInts,
        'readFloat':  readFloat,  'readAllFloats':  readAllFloats,
        'readBool':   readBool,   'readAllBools':   readAllBools,
        'readString': readString, 'readAllStrings': readAllStrings,
        'readLine':   readLine,   'readAllLines' :  readAllLines,
        'readAll':    readAll }

    testId = sys.argv[1]

    if testId == 'write':
        _testWrite()
    else:
        writeln(map[testId]()) 
Example 2
Project: charm-plumgrid-gateway   Author: openstack   File: unitdata.py View Source Project 6 votes vote down vote up
def hook_scope(self, name=""):
        """Scope all future interactions to the current hook execution
        revision."""
        assert not self.revision
        self.cursor.execute(
            'insert into hooks (hook, date) values (?, ?)',
            (name or sys.argv[0],
             datetime.datetime.utcnow().isoformat()))
        self.revision = self.cursor.lastrowid
        try:
            yield self.revision
            self.revision = None
        except:
            self.flush(False)
            self.revision = None
            raise
        else:
            self.flush() 
Example 3
Project: alfred-mpd   Author: deanishe   File: docopt.py View Source Project 6 votes vote down vote up
def parse_argv(tokens, options, options_first=False):
    """Parse command-line argument vector.

    If options_first:
        argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
    else:
        argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;

    """
    parsed = []
    while tokens.current() is not None:
        if tokens.current() == '--':
            return parsed + [Argument(None, v) for v in tokens]
        elif tokens.current().startswith('--'):
            parsed += parse_long(tokens, options)
        elif tokens.current().startswith('-') and tokens.current() != '-':
            parsed += parse_shorts(tokens, options)
        elif options_first:
            return parsed + [Argument(None, v) for v in tokens]
        else:
            parsed.append(Argument(None, tokens.move()))
    return parsed 
Example 4
Project: Cortex-Analyzers   Author: CERT-BDF   File: pdfid.py View Source Project 6 votes vote down vote up
def LoadPlugins(plugins, verbose):
    if plugins == '':
        return
    scriptPath = os.path.dirname(sys.argv[0])
    for plugin in sum(map(ProcessAt, plugins.split(',')), []):
        try:
            if not plugin.lower().endswith('.py'):
                plugin += '.py'
            if os.path.dirname(plugin) == '':
                if not os.path.exists(plugin):
                    scriptPlugin = os.path.join(scriptPath, plugin)
                    if os.path.exists(scriptPlugin):
                        plugin = scriptPlugin
            exec(open(plugin, 'r').read())
        except Exception as e:
            print('Error loading plugin: %s' % plugin)
            if verbose:
                raise e 
Example 5
Project: python-   Author: secondtonone1   File: sandbox.py View Source Project 6 votes vote down vote up
def run_setup(setup_script, args):
    """Run a distutils setup script, sandboxed in its directory"""
    setup_dir = os.path.abspath(os.path.dirname(setup_script))
    with setup_context(setup_dir):
        try:
            sys.argv[:] = [setup_script] + list(args)
            sys.path.insert(0, setup_dir)
            # reset to include setup dir, w/clean callback list
            working_set.__init__()
            working_set.callbacks.append(lambda dist: dist.activate())

            # __file__ should be a byte string on Python 2 (#712)
            dunder_file = (
                setup_script
                if isinstance(setup_script, str) else
                setup_script.encode(sys.getfilesystemencoding())
            )

            with DirectorySandbox(setup_dir):
                ns = dict(__file__=dunder_file, __name__='__main__')
                _execfile(setup_script, ns)
        except SystemExit as v:
            if v.args and v.args[0]:
                raise
            # Normal exit, just return 
Example 6
Project: python-   Author: secondtonone1   File: launch.py View Source Project 6 votes vote down vote up
def run():
    """
    Run the script in sys.argv[1] as if it had
    been invoked naturally.
    """
    __builtins__
    script_name = sys.argv[1]
    namespace = dict(
        __file__=script_name,
        __name__='__main__',
        __doc__=None,
    )
    sys.argv[:] = sys.argv[1:]

    open_ = getattr(tokenize, 'open', open)
    script = open_(script_name).read()
    norm_script = script.replace('\\r\\n', '\\n')
    code = compile(norm_script, script_name, 'exec')
    exec(code, namespace) 
Example 7
Project: python-   Author: secondtonone1   File: easy_install.py View Source Project 6 votes vote down vote up
def main(argv=None, **kw):
    from setuptools import setup
    from setuptools.dist import Distribution

    class DistributionWithoutHelpCommands(Distribution):
        common_usage = ""

        def _show_help(self, *args, **kw):
            with _patch_usage():
                Distribution._show_help(self, *args, **kw)

    if argv is None:
        argv = sys.argv[1:]

    with _patch_usage():
        setup(
            script_args=['-q', 'easy_install', '-v'] + argv,
            script_name=sys.argv[0] or 'easy_install',
            distclass=DistributionWithoutHelpCommands,
            **kw
        ) 
Example 8
Project: python-   Author: secondtonone1   File: base64.py View Source Project 6 votes vote down vote up
def main():
    """Small main program"""
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'deut')
    except getopt.error as msg:
        sys.stdout = sys.stderr
        print(msg)
        print("""usage: %s [-d|-e|-u|-t] [file|-]
        -d, -u: decode
        -e: encode (default)
        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
        sys.exit(2)
    func = encode
    for o, a in opts:
        if o == '-e': func = encode
        if o == '-d': func = decode
        if o == '-u': func = decode
        if o == '-t': test(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout.buffer)
    else:
        func(sys.stdin.buffer, sys.stdout.buffer) 
Example 9
Project: cbapi-examples   Author: cbcommunity   File: group_datasharing_del_all.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.group_id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    #check if the given group_id truly corresponds to one of the existing sensor groups
    does_exist = False
    for group in cb.group_enum():
        if int(opts.group_id) == int(group['id']):
            does_exist = True

    if does_exist:
        config = cb.group_datasharing_del_all(opts.group_id)

        for key in config.keys():
            print "%-20s : %s" % (key, config[key])
    else:
        sys.exit(-1) 
Example 10
Project: cbapi-examples   Author: cbcommunity   File: watchlist_enum.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # enumerate all watchlists 
    #
    watchlists = cb.watchlist() 

    print "%-4s | %-32s | %s" % ('id', 'name', 'query')
    print "%-4s + %-32s + %s" % ('-' * 4, '-' * 32, '-' * 60)

    # for each result 
    for watchlist in watchlists:
        print "%-4s | %-32s | %s" % (watchlist['id'], watchlist['name'], truncate(opts.fulloutput, watchlist['search_query'], 57)) 
Example 11
Project: cbapi-examples   Author: cbcommunity   File: group_get_linux.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    builds = cb.get_builds()
    for build in builds:
        print ""
        for key in build.keys():
            print "%-20s : %s" % (key, build[key]) 
Example 12
Project: cbapi-examples   Author: cbcommunity   File: check_ioc.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.fname or not opts.type:
        print "Missing required param."
        sys.exit(-1)

    if not opts.type in ["md5", "domain", "ipaddr"]:
        print "Unknown type: ", opts.type
        sys.exit(-1)

    # setup the CbApi object
    cb = CBQuery(opts.url, opts.token, ssl_verify=opts.ssl_verify)

    # get the IOCs to check; this is a list of strings, one indicator
    # per line.  strip off the newlines as they come in
    vals = [val.strip() for val in open(opts.fname, "r")]

    # check each!
    cb.check(vals, opts.type, opts.detail) 
Example 13
Project: cbapi-examples   Author: cbcommunity   File: feed_enum.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    # enumerate configured feeds
    #
    feeds = cb.feed_enum()

    # output a banner
    #
    print "%-3s  %-25s   %-8s   %s" % ("Id", "Name", "Enabled", "Url")
    print "%s+%s+%s+%s" % ("-"*3, "-"*27, "-"*10, "-"*31)

    # output a row about each feed
    #
    for feed in feeds:
        print "%-3s| %-25s | %-8s | %s" % (feed['id'], feed['name'], feed['enabled'], feed['feed_url']) 
Example 14
Project: cbapi-examples   Author: cbcommunity   File: group_get_windowsexe.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    builds = cb.get_builds()
    for build in builds:
        print ""
        for key in build.keys():
            print "%-20s : %s" % (key, build[key]) 
Example 15
Project: cbapi-examples   Author: cbcommunity   File: watchlist_edit.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id or not opts.query:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # edit the search query of the just-added watchlist
    #
    watchlist = { 'search_query': opts.query }
    print "-> Modifying the watchlist query..."
    cb.watchlist_modify(opts.id, watchlist)
    print "-> Watchlist modified" 

    # get record describing this watchlist  
    #
    print "-> Querying for watchlist information..."
    watchlist = cb.watchlist(opts.id)
    print "-> Watchlist queried; details:" 
    watchlist_output(watchlist) 
Example 16
Project: cbapi-examples   Author: cbcommunity   File: sensor_info.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.sensorid:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # enumerate sensors 
    #
    sensor = cb.sensor(opts.sensorid)

    # output
    #
    for key in sensor.keys():
        print "%-35s : %s" % (key, sensor[key]) 
Example 17
Project: cbapi-examples   Author: cbcommunity   File: sensor_backlog_aggregate.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # if a period is specified, handle that specially
    #
    if 0 != opts.interval:
        return query_forever(cb, opts.interval, opts.udp)

    # grab the global statistics 
    #
    backlog = cb.sensor_backlog()

    # output
    #
    for key in backlog.keys():
        print "%-35s : %s" % (key, backlog[key]) 
Example 18
Project: cbapi-examples   Author: cbcommunity   File: feed_action_enum.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    actions = cb.feed_action_enum(opts.id)
    count = 1
    for action in actions:
        print ""
        print "Action number: %s" % count
        print "-"*50
        count += 1
        for key in action.keys():
            print "%-20s : %s" % (key, action[key]) 
Example 19
Project: cbapi-examples   Author: cbcommunity   File: binary_download.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or opts.md5 is None:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    if opts.filename is None:
        opts.filename = "%s.zip" % (opts.md5,)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # perform a single binary search
    #
    binary = cb.binary(opts.md5)
    
    # open the file and write out the contents
    #
    open(opts.filename, "w").write(binary)

    print "-> Downloaded binary %s [%u bytes]" % (opts.md5, len(binary)) 
Example 20
Project: cbapi-examples   Author: cbcommunity   File: feed_synchronize.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.feedname:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    id = cb.feed_get_id_by_name(opts.feedname)
    if id is None:
        print "-> No configured feed with name '%s' found!" % (opts.feedname)
        sys.exit(-1)

    sync_result = cb.feed_synchronize(opts.feedname, True)
    print sync_result 
Example 21
Project: cbapi-examples   Author: cbcommunity   File: watchlist_remove_all_newerThanID.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    watchlists = cb.watchlist()

    watchlist_int_param = int(opts.id)

    # for each result
    for watchlist in watchlists:
	watchlist_int_id = int(watchlist['id'])
	#print "watchlist['id']: %s, opts.id: %s" % (watchlist_int_id,watchlist_int_param,)
	if watchlist_int_id >= watchlist_int_param:
		#print "MATCH: watchlist['id']: %s > opts.id: %s" % (watchlist_int_id,watchlist_int_param,)
            	print "-> Deleting watchlist [id=%s]: %s" % (watchlist_int_id,watchlist['name'],)
            	watchlist = cb.watchlist_del(watchlist_int_id)
            	print "-> Watchlist deleted" 
Example 22
Project: cbapi-examples   Author: cbcommunity   File: watchlist_del.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # delete the watchlist
    # for the purposes of this test script, hardcode the watchlist type, name, and query string
    #
    print "-> Deleting watchlist [id=%s]..." % (opts.id,)
    watchlist = cb.watchlist_del(opts.id)
    print "-> Watchlist deleted" 
Example 23
Project: cbapi-examples   Author: cbcommunity   File: process_report.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.fname or not opts.id:
        print "Missing required param."
        sys.exit(-1)

    # setup the CbApi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    print "-> querying for report for id '%s'..." % (opts.id)
    report = cb.process_report(opts.id, opts.segment)

    print "-> writing report to file '%s'..." % (opts.fname)
    open(opts.fname, "w").write(report)

    print "-> Complete" 
Example 24
Project: cbapi-examples   Author: cbcommunity   File: event_info.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    events = cb.event_info(opts.id)
    print events
    print ""
    count = 1
    for event in events:
        print ""
        print "Event Number: %s" % count
        count = count + 1
        for field in event:
                print "%-20s : %s" % (field, event[field]) 
Example 25
Project: cbapi-examples   Author: cbcommunity   File: feed_modify.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or (not opts.feedname and not opts.feedid):
        print "Missing required param; run with --help for usage"
        print "One of -f or -i must be specified"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    if not opts.feedid:
      id = cb.feed_get_id_by_name(opts.feedname)
      if id is None:
        print "-> No configured feed with name '%s' found!" % (opts.feedname)
        return
    else:
      id = opts.feedid
      old_feed = cb.feed_info(id)

      #create a new updated feed based on user input

    # create 
Example 26
Project: cbapi-examples   Author: cbcommunity   File: group_get_osx.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    builds = cb.get_builds()
    for build in builds:
        print ""
        for key in build.keys():
            print "%-20s : %s" % (key, build[key]) 
Example 27
Project: cbapi-examples   Author: cbcommunity   File: group_datasharing_info.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.group_id or not opts.config_id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    #check if the given group_id truly corresponds to one of the existing sensor groups
    does_exist = False
    for group in cb.group_enum():
        if int(opts.group_id) == int(group['id']):
            does_exist = True

    if does_exist:
        datasharing_config = cb.group_datasharing_info(opts.group_id, opts.config_id)

        for key in datasharing_config.keys():
            print "%-20s : %s" % (key, datasharing_config[key])
    else:
        sys.exit(-1) 
Example 28
Project: cbapi-examples   Author: cbcommunity   File: event_update.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id or not opts.description:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    event = cb.event_update(opts.id, opts.description)
    print ""
    for key in event.keys():
        print "%-20s : %s" % (key, event[key]) 
Example 29
Project: cbapi-examples   Author: cbcommunity   File: alert_search.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)
    start = 0
    pagesize=100
    while True:
        results = cb.alert_search(opts.query, rows=int(pagesize), start=start)
        if len(results['results']) == 0: break
        for result in results['results']:
            pprint.pprint(result)
        start = start + int(pagesize) 
Example 30
Project: cbapi-examples   Author: cbcommunity   File: event_add.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.investigation_id or not opts.description or not opts.start_date:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    event = cb.event_add(opts.investigation_id, opts.description, opts.start_date)
    print ""
    print "-->Event Added:"
    for key in event.keys():
            print "%-20s : %s" % (key, event[key]) 
Example 31
Project: cbapi-examples   Author: cbcommunity   File: feed_requirements.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    requirements = cb.feed_requirements(opts.id)
    for requirement in requirements:
        print requirement

    sync_result = cb.feed_synchronize(opts.feedname, True)
    print sync_result 
Example 32
Project: cbapi-examples   Author: cbcommunity   File: event_del.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    event = cb.event_del(opts.id)
    print ""
    for key in event.keys():
        print "%-20s : %s" % (key, event[key]) 
Example 33
Project: cbapi-examples   Author: cbcommunity   File: download_sensor_installer.py View Source Project 6 votes vote down vote up
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.type or not opts.group or not opts.filename:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # download the installer package 
    #
    print "-> Downloading..."
    bytes = cb.sensor_installer(opts.type, opts.group)
    print "-> Sensor Installer Package is %s bytes" % (len(bytes))
    print "-> Download complete"

    # save the instaler package to disk
    #
    print "-> Saving to %s..." % (opts.filename)
    open(opts.filename, 'wb').write(bytes)
    print "-> Complete" 
Example 34
Project: rca-evaluation   Author: sieve-microservices   File: example.py View Source Project 6 votes vote down vote up
def main():
    if len(sys.argv) < 2:
        sys.stderr.write("USAGE: %s measurement\n" % sys.argv[0])
        sys.exit(1)
    path = sys.argv[1]

    with open(os.path.join(path, "metadata.json")) as f:
        metadata = json.load(f)
        start = date(metadata["start"][:-1])
        end = date(metadata["start"][:-1])
        print('open measurement "%s" from "%s" to "%s"', metadata["name"], start, end)
        for service in metadata["services"]:
            print('open service "%s"' % service["name"])
            with open(os.path.join(path, service["filename"])) as csvfile:
                r = csv.DictReader(csvfile, dialect=csv.excel_tab)
                for row in r:
                    print(row["time"]) 
Example 35
Project: python-opilo-script   Author: SEEDTEAM   File: opilo-sms.py View Source Project 6 votes vote down vote up
def sms():
    if len(sys.argv) < 2:
        print(help_text)
        return
    if sys.argv[1] == "send":
        if len(sys.argv) < 3:
            print("????? ????? ?? ?? ???.")
            return
        if not re.match(r"[\+98|0]9[0-9]*",sys.argv[2]):
            print("????? ???? ??? ?????? ???.tetete")
            return
        number = sys.argv[2]
        if re.match(sys.argv[2], r"^\+98"):
            number = re.sub("+98", "0", number)
        text = sys.argv[3]
        if len(text) > 100:
            print("????? ??????? ??? ??? ????? ???? ???.")
            return
        send_sms(number, text, str(time.time()))
        return
    if sys.argv[1] == "credits":
        get_credits()
        return 
Example 36
Project: IotCenter   Author: panjanek   File: app.py View Source Project 6 votes vote down vote up
def __init__(self, config):
        self.service = None
        self.webServer = None
        self.config = config
        self.httpsPort = int(self.config.get('web', 'httpsPort'))
        self.httpPort = int(self.config.get('web', 'httpPort'))        
        self.adminPasswordHash = self.config.get('web', 'adminPasswordHash')
        self.apiSecret = self.config.get('web', 'apiSecret')
        self.uploadDir = self.config.get('web', 'uploadDir')
        self.dbFile = self.config.get('web', 'dbFile')
        self.httpsCertFile = self.config.get('web', 'httpsCertFile')
        self.httpsKeyFile = self.config.get('web', 'httpsKeyFile')
        self.httpsChainFile = self.config.get('web', 'httpsChainFile')
        self.localVideoPort = int(self.config.get('web', 'localVideoPort'))
        dir = os.path.dirname(os.path.realpath(sys.argv[0]))        
        self.database = database.Database(self.dbFile)
        self.deviceConfig = dict()
        for deviceId, jsonConf in dict(self.config.items('devices')).iteritems():
            self.deviceConfig[deviceId] = json.loads(jsonConf, object_pairs_hook=OrderedDict)
        self.trends = dict()
        self.lock = threading.Lock() 
Example 37
Project: kas   Author: siemens   File: kas.py View Source Project 6 votes vote down vote up
def kas(argv):
    """
        The main entry point of kas.
    """
    create_logger()

    parser = kas_get_argparser()
    args = parser.parse_args(argv)

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    logging.info('%s %s started', os.path.basename(sys.argv[0]), __version__)

    loop = asyncio.get_event_loop()

    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, interruption)
    atexit.register(_atexit_handler)

    for plugin in getattr(kasplugin, 'plugins', []):
        if plugin().run(args):
            return

    parser.print_help() 
Example 38
Project: stalker_pyramid   Author: eoyilmaz   File: initializedb.py View Source Project 6 votes vote down vote up
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)

    from pyramid.paster import get_appsettings, setup_logging
    from stalker import db

    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)

    db.setup(settings)
    db.init()

    # create statuses
    create_statuses_and_status_lists()
    create_ticket_types() 
Example 39
Project: my-first-blog   Author: AnkurBegining   File: sandbox.py View Source Project 6 votes vote down vote up
def run_setup(setup_script, args):
    """Run a distutils setup script, sandboxed in its directory"""
    setup_dir = os.path.abspath(os.path.dirname(setup_script))
    with setup_context(setup_dir):
        try:
            sys.argv[:] = [setup_script] + list(args)
            sys.path.insert(0, setup_dir)
            # reset to include setup dir, w/clean callback list
            working_set.__init__()
            working_set.callbacks.append(lambda dist: dist.activate())

            # __file__ should be a byte string on Python 2 (#712)
            dunder_file = (
                setup_script
                if isinstance(setup_script, str) else
                setup_script.encode(sys.getfilesystemencoding())
            )

            with DirectorySandbox(setup_dir):
                ns = dict(__file__=dunder_file, __name__='__main__')
                _execfile(setup_script, ns)
        except SystemExit as v:
            if v.args and v.args[0]:
                raise
            # Normal exit, just return 
Example 40
Project: my-first-blog   Author: AnkurBegining   File: launch.py View Source Project 6 votes vote down vote up
def run():
    """
    Run the script in sys.argv[1] as if it had
    been invoked naturally.
    """
    __builtins__
    script_name = sys.argv[1]
    namespace = dict(
        __file__=script_name,
        __name__='__main__',
        __doc__=None,
    )
    sys.argv[:] = sys.argv[1:]

    open_ = getattr(tokenize, 'open', open)
    script = open_(script_name).read()
    norm_script = script.replace('\\r\\n', '\\n')
    code = compile(norm_script, script_name, 'exec')
    exec(code, namespace) 
Example 41
Project: my-first-blog   Author: AnkurBegining   File: easy_install.py View Source Project 6 votes vote down vote up
def main(argv=None, **kw):
    from setuptools import setup
    from setuptools.dist import Distribution

    class DistributionWithoutHelpCommands(Distribution):
        common_usage = ""

        def _show_help(self, *args, **kw):
            with _patch_usage():
                Distribution._show_help(self, *args, **kw)

    if argv is None:
        argv = sys.argv[1:]

    with _patch_usage():
        setup(
            script_args=['-q', 'easy_install', '-v'] + argv,
            script_name=sys.argv[0] or 'easy_install',
            distclass=DistributionWithoutHelpCommands,
            **kw
        ) 
Example 42
Project: my-first-blog   Author: AnkurBegining   File: build_meta.py View Source Project 6 votes vote down vote up
def build_wheel(wheel_directory, config_settings=None,
                metadata_directory=None):
    config_settings = _fix_config(config_settings)
    wheel_directory = os.path.abspath(wheel_directory)
    sys.argv = sys.argv[:1] + ['bdist_wheel'] + \
        config_settings["--global-option"]
    _run_setup()
    if wheel_directory != 'dist':
        shutil.rmtree(wheel_directory)
        shutil.copytree('dist', wheel_directory)

    wheels = [f for f in os.listdir(wheel_directory)
              if f.endswith('.whl')]

    assert len(wheels) == 1
    return wheels[0] 
Example 43
Project: core-framework   Author: RedhawkSDR   File: scatest.py View Source Project 6 votes vote down vote up
def __init__(self, methodName='runTest', orbArgs=[]):
        unittest.TestCase.__init__(self, methodName)
        args = sys.argv
        self.debuglevel = 3
        for arg in args:
            if '--debuglevel' in arg:
                self.debuglevel = arg.split('=')[-1]
        self._orb = CORBA.ORB_init(sys.argv + orbArgs, CORBA.ORB_ID)
        self._poa = self._orb.resolve_initial_references("RootPOA")
        self._poa._get_the_POAManager().activate()
        self._ns = self._orb.resolve_initial_references("NameService")
        self._root = self._ns._narrow(CosNaming.NamingContext)

        # Maintain a registry of the DomainManager (there should normally be just one)
        # and all spawned DeviceManagers, for easy cleanup.
        self._domainBooter = None
        self._domainManager = None

        self._deviceLock = threading.Lock()
        self._deviceBooters = []
        self._deviceManagers = []
        self._execparams = "" 
Example 44
Project: core-framework   Author: RedhawkSDR   File: qtbrowse.py View Source Project 6 votes vote down vote up
def main():
    # Set up a console logger.
    console = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(name)-12s:%(levelname)-8s: %(message)s")
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    logging.getLogger().setLevel(logging.INFO)

    kw = {}
    longopts = ['domainname=', 'verbose']
    opts, args = getopt.getopt(sys.argv[1:], 'v', longopts)
    for opt, val in opts:
        if opt == '--domainname':
            kw['domainName'] = val
        if opt in ['-v', '--verbose']:
            kw['verbose'] = True

    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = BrowseWindow(**kw)
    w.show()
    a.exec_() 
Example 45
Project: charm-swift-proxy   Author: openstack   File: unitdata.py View Source Project 6 votes vote down vote up
def hook_scope(self, name=""):
        """Scope all future interactions to the current hook execution
        revision."""
        assert not self.revision
        self.cursor.execute(
            'insert into hooks (hook, date) values (?, ?)',
            (name or sys.argv[0],
             datetime.datetime.utcnow().isoformat()))
        self.revision = self.cursor.lastrowid
        try:
            yield self.revision
            self.revision = None
        except Exception:
            self.flush(False)
            self.revision = None
            raise
        else:
            self.flush() 
Example 46
Project: charm-swift-proxy   Author: openstack   File: unitdata.py View Source Project 6 votes vote down vote up
def hook_scope(self, name=""):
        """Scope all future interactions to the current hook execution
        revision."""
        assert not self.revision
        self.cursor.execute(
            'insert into hooks (hook, date) values (?, ?)',
            (name or sys.argv[0],
             datetime.datetime.utcnow().isoformat()))
        self.revision = self.cursor.lastrowid
        try:
            yield self.revision
            self.revision = None
        except Exception:
            self.flush(False)
            self.revision = None
            raise
        else:
            self.flush() 
Example 47
Project: data_pipeline   Author: Yelp   File: refresh_manager.py View Source Project 6 votes vote down vote up
def _init_global_state(self):
        if self.options.database is None:
            raise ValueError("--database is required to be defined")
        self.cluster = self.options.cluster
        self.database = self.options.database
        self.namespace = DBSourcedNamespace(
            cluster=self.cluster,
            database=self.database
        ).get_name()
        self.config_path = self.options.config_path
        self.dry_run = self.options.dry_run
        self.per_source_throughput_cap = self.options.per_source_throughput_cap
        self.total_throughput_cap = self.options.total_throughput_cap
        load_package_config(self.config_path)
        self.refresh_runner_path = self.get_refresh_runner_path()
        # Removing the cmd line arguments to prevent child process error.
        sys.argv = sys.argv[:1] 
Example 48
Project: attract-repel   Author: nmrksic   File: attract-repel.py View Source Project 5 votes vote down vote up
def main():
    """
    The user can provide the location of the config file as an argument. 
    If no location is specified, the default config file (experiment_parameters.cfg) is used.
    """
    try:
        config_filepath = sys.argv[1]
    except:
        print "\nUsing the default config file: experiment_parameters.cfg\n"
        config_filepath = "experiment_parameters.cfg"

    run_experiment(config_filepath) 
Example 49
Project: charm-plumgrid-gateway   Author: openstack   File: pg_gw_hooks.py View Source Project 5 votes vote down vote up
def main():
    try:
        hooks.execute(sys.argv)
    except UnregisteredHookError as e:
        log('Unknown hook {} - skipping.'.format(e)) 
Example 50
Project: charm-plumgrid-gateway   Author: openstack   File: hookenv.py View Source Project 5 votes vote down vote up
def hook_name():
    """The name of the currently executing hook"""
    return os.environ.get('JUJU_HOOK_NAME', os.path.basename(sys.argv[0]))