Beispiel #1
0
def parseArgs(argv):
   '''
   Parses command line arguments
   '''

   opt_args= ['start', 'stop', 'restart']

   optParser= OptionParser()

   [ optParser.add_option(opt) for opt in [
      make_option('-f', '--foreground', action='store_true', dest= 'foreground', default= False, help= 'run in foreground'),
      make_option('-q', '--queue', default= 'localhost:50001:impetus', help= 'queue ip:port:key'),
      make_option('-d', '--dfs', default= 'localhost:50002:impetus', help= 'dfs ip:port:key'),
      make_option('-s', '--s3', default= None, help= '<accessKey>:<secretKey>:<bucket> for s3 transport'),
      make_option('-p', '--pidDir', default= path.join(getcwd(), '../pid'), help= 'path to pid directory'),
      make_option('-o', '--logDir', default= path.join(getcwd(), '../log'), help= 'path to log directory'),
      make_option('-t', '--taskDir', default= path.join(getcwd(), '../tasks'), help= 'path to task directory'),
      make_option('-m', '--maxProcesses', default= 25, type= int, help= 'path to pid directory'),
      make_option('-n', '--sleep', default= 0.01, type= float, help= 'sleep time for waits')
   ]]

   optParser.set_usage('%%prog %s' % ('|'.join(opt_args)))

   opts, args= optParser.parse_args()
   if not opts.foreground and len(args) < 1:
      optParser.print_usage()
      exit(-1)

   setattr(opts, 'PIDFile', path.join(opts.pidDir, argv[0].replace('.py', '.pid')))

   if opts.dfs == 'None':
      opts.dfs = None

   return args, opts, optParser.print_usage, optParser.print_help
def parse_args():
    parser = OptionParser()
    parser.set_usage("rhn-custom-info [options] key1 value1 key2 value2 ...")
    parser.add_option("-u", "--username",
                      action="store", type="string", dest="username",
                      help="your RHN username", metavar="RHN_LOGIN")

    parser.add_option("-p", "--password",
                      action="store", type="string", dest="password",
                      help="your RHN password", metavar="RHN_PASSWD")

    parser.add_option("-s", "--server-url",
                      action="store", type="string", dest="url",
                      help="use the rhn api at URL", metavar="URL")

    parser.add_option("-d", "--delete-values",
                      action="store_true", dest="delete_values", default=0,
                      help="delete one or multiple custom keys from the system")

    parser.add_option("-l", "--list-values",
                      action="store_true", dest="list_values", default=0,
                      help="list the custom keys and values for the system",
                      )


    return parser.parse_args()
def CreateCommandLineParser():
    parser = OptionParser()
    usage = sys.argv[0] + " command [args] [options]"
    usage += "\n\nCommands:"
    usage += "\n  init [projects ...]       Initialize local copies of projects"
    usage += "\n  list                      List contents of INI file"
    usage += "\n  status [projects ...]     Get current project status"
    usage += "\n  history [projects ...]    Get time and outcome of previous syncs"
    usage += "\n  sync [projects ...]       Perform synchronisation"
    parser.set_usage(usage)
    parser.add_option('-i', '--ini', type='string', dest='ini_filename',
                      help='INI file name')
    parser.add_option('-d', '--direction', dest='direction',
                      choices=['push', 'pull', 'both'],
                      help='Direction(s) of the synchronisation operation (push|pull|both)')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                      default=False, help='Verbose output')
    parser.add_option('-q', '--quiet', dest='quiet', action='store_true',
                      default=False, help='No output')
    parser.add_option('-n', '--dry-run', dest='dry_run', action='count',
                      default=0, help='Do not actually execute any actions')
    parser.add_option('-a', '--all', dest='all', action='store_true',
              default=False, help='Sync all projects, including those with auto=false')
    parser.add_option('-r', '--remote', dest='remote',
                      help="Name of remote")
    parser.add_option('-p', '--prefer', dest='prefer',
                      help="Which copy to prefer in case of conflict (local|remote)")

    return parser
Beispiel #4
0
def parseArguments(argv, print_help=True):
    ENABLE_DEFAULT_HELP_MESSAGE = False
    command = None

    if len(argv) >= 2:
        arg1 = argv[1]
        for cursor in CMD_MAP.keys():
            if cursor == arg1:
                command = cursor
                argv.pop(1)
                break

    parser = OptionParser(add_help_option=ENABLE_DEFAULT_HELP_MESSAGE)
    parser.set_usage('Usage: opm {COMMAND} {OPTIONS}')
    parser.add_option('-c', '--config-path',
                      dest='config_path',
                      metavar='PATH',
                      default=CONFIG_XML_PATH,
                      help='Set the configure file path.')
    options, args = parser.parse_args(argv)

    if print_help is True and (command is None or command == CMD_HELP):
        parser.print_help()
        printCommandHelp()

    return command, options
Beispiel #5
0
class Attach():
	def __init__(self):
		self.git = Git()
		self.parser = OptionParser()
		self.parser.set_usage("mgit attach <subproject name>")

	def print_usage(self):
		self.parser.print_usage()

	def run(self, args):
		options, args = self.parser.parse_args(args[1:])
		if len(args) <= 0:
			self.parser.print_usage()
			return
	
		if len(args) > 1:
			module = args[1]
		else:
			module = self.git.module_name(args[0])
		if module == None or len(module) <= 0:
			return

		if not os.path.exists(module):
			print("module %s not exists." % module)
			return

		project = Project()
		project.append(module)
def main():
	parser = OptionParser(conflict_handler="resolve")
	parser.set_usage("mail-instance-creator.py <from-email-address> <to-email-address> <languagecode> <wikiaddress>\n\n\texample: mail-instance-creator.py '*****@*****.**' 'es' 'http://example.com/w/'")

	(options, args) = parser.parse_args()

	if len(args) != 4:
		parser.error("mail-instance-creator.py expects exactly four arguments.")

	fromaddress = args[0]
	toaddress = args[1]
	lang = args[2]
	wikiaddress = args[3]
	subjecturl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-subject/' + lang + '}}&format=xml'
	bodyurl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-body/' + lang + '}}&format=xml'
	dom = minidom.parse(urllib.urlopen(subjecturl))
	subject = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	dom = minidom.parse(urllib.urlopen(bodyurl))
	body = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	body = body + ' ' + gethostname()
	sendmail_location = "/usr/sbin/sendmail" # sendmail location
	p = os.popen("%s -t" % sendmail_location, "w")
	p.write("From: %s\n" % fromaddress)
	p.write("To: %s\n" % toaddress)
	p.write("Subject: %s\n" % subject)
	p.write("\n") # blank line separating headers from body
	p.write(body)
	status = p.close()
	return status
Beispiel #7
0
def parse():
    p = OptionParser()
    p.set_usage("command [options] privatekey")
    p.add_option('-p', '--publickey', dest = 'publickey', default = './p.pub')
    #p.add_option('-v', '--private', dest = 'vf')
    p.add_option('-t', '--type', dest = 'type', default = 'ssh-rsa')
    return p
Beispiel #8
0
    def optParse():
        """
        Parses command line options.

        Generally we're supporting all the command line options that doxypy.py
        supports in an analogous way to make it easy to switch back and forth.
        We additionally support a top-level namespace argument that is used
        to trim away excess path information.
        """

        parser = OptionParser(prog=basename(argv[0]))

        parser.set_usage("%prog [options] filename")
        parser.add_option(
            "-a", "--autobrief",
            action="store_true", dest="autobrief",
            help="parse the docstring for @brief description and other information"
        )
        parser.add_option(
            "-c", "--autocode",
            action="store_true", dest="autocode",
            help="parse the docstring for code samples"
        )
        parser.add_option(
            "-n", "--ns",
            action="store", type="string", dest="topLevelNamespace",
            help="specify a top-level namespace that will be used to trim paths"
        )
        parser.add_option(
            "-t", "--tablength",
            action="store", type="int", dest="tablength", default=4,
            help="specify a tab length in spaces; only needed if tabs are used"
        )
        group = OptionGroup(parser, "Debug Options")
        group.add_option(
            "-d", "--debug",
            action="store_true", dest="debug",
            help="enable debug output on stderr"
        )
        parser.add_option_group(group)

        ## Parse options based on our definition.
        (options, filename) = parser.parse_args()

        # Just abort immediately if we are don't have an input file.
        if not filename:
            stderr.write("No filename given." + linesep)
            sysExit(-1)

        # Turn the full path filename into a full path module location.
        fullPathNamespace = filename[0].replace(sep, '.')[:-3]
        # Use any provided top-level namespace argument to trim off excess.
        realNamespace = fullPathNamespace
        if options.topLevelNamespace:
            namespaceStart = fullPathNamespace.find(options.topLevelNamespace)
            if namespaceStart >= 0:
                realNamespace = fullPathNamespace[namespaceStart:]
        options.fullPathNamespace = realNamespace

        return options, filename[0]
def cmd_line():
    parser = OptionParser()
    parser.set_usage("yum-debug-restore [options]")
    parser.add_option("-C", "--cache", action="store_true",
                      help="run from cache only")
    parser.add_option("-c", dest="conffile", help="config file location")
    parser.add_option("--enablerepo", action="append", dest="enablerepos",
                      help="specify additional repoids to query, can be specified multiple times")
    parser.add_option("--disablerepo", action="append", dest="disablerepos",
                      help="specify repoids to disable, can be specified multiple times")                      
    parser.add_option("-y", dest="assumeyes", action="store_true",
                      help="answer yes for all questions")
    parser.add_option("--skip-broken", action="store_true",
                      help="skip packages with depsolving problems")

    parser.add_option("--output", action="store_true",
                      help="output the yum shell commands")
    parser.add_option("--shell", 
                      help="output the yum shell commands to a file")

    parser.add_option("--install-latest", action="store_true",
                      help="install the latest instead of specific versions")
    parser.add_option("--ignore-arch", action="store_true",
                      help="ignore arch of packages, so you can dump on .i386 and restore on .x86_64")

    parser.add_option("--filter-types", 
                      help="Limit to: install, remove, update, downgrade")

    (opts, args) = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit(1)
    return (opts, args)
Beispiel #10
0
def main():

    #args = sys.argv
    parser = OptionParser()
    parser.set_usage(_("Usage:  billreminder [OPTIONS...]"))
    parser.add_option('-v','--version', action='store_true', dest='app_version', default=False, help=_('Displays the version number for this application.'))
    parser.add_option('--about', action='store_true', dest='app_about', default=False, help=_('About this application.'))
    parser.add_option('--add', action='store_true', dest='app_add', default=False, help=_('Adds a new bill to the database.'))
    parser.add_option('--standalone', action='store_true', dest='app_standalone', default=False, help=_('Access database directly, without daemon.'))

    # Verify arguments
    options, args = parser.parse_args()
    if options.app_about:
        dialogs.about_dialog()
    elif options.app_add:
        print dialogs.add_dialog()
    elif options.app_standalone:
        print _("This option is not implemented yet.")
    elif options.app_version:
        print _("This is %(appname)s - Version: %(version)s") % \
                         {'appname': common.APPNAME,
                          'version': common.APPVERSION}
    else:
        gtk.gdk.threads_init()
        app = BillReminder()
        gtk.main()
def parse_commandline():
    """Parse the comandline and return parsed options."""

    parser = OptionParser()
    parser.description = __doc__

    parser.set_usage("usage: %prog [options] (list|add|remove) [collaborator]." "\nTry %prog --help for details.")
    parser.add_option("-d", "--debug", action="store_true", help="Enables debugging mode")
    parser.add_option("-c", "--cache", default=None, help="Location for network cache [default: None]")
    parser.add_option("-l", "--login", help="Username to login with")
    parser.add_option(
        "-a", "--account", help="User owning the repositories to be changed " "[default: same as --login]"
    )
    parser.add_option(
        "-t", "--apitoken", help="API Token - can be found on the lower right of " "https://github.com/account"
    )

    options, args = parser.parse_args()
    if len(args) not in [1, 2]:
        parser.error("wrong number of arguments")
    if len(args) == 1 and args[0] in ["add", "remove"]:
        parser.error("%r needs a collaborator name as second parameter\n" % args[0])
    elif len(args) == 1 and args[0] != "list":
        parser.error('unknown command %r. Try "list", "add" or "remove"\n' % args[0])
    if len(args) == 2 and args[0] not in ["add", "remove"]:
        parser.error('unknown command %r. Try "list", "add" or "remove"\n' % args[0])
    if not options.login:
        parser.error("you must provide --login information\n")

    return options, args
def parse_args():
    parser = OptionParser()
    parser.add_option("--snapshot-file", default=None,
                      help="Path to the test-warehouse archive")
    parser.add_option("--cm-user", default="admin", help="Cloudera Manager admin user")
    parser.add_option("--cm-pass", default="admin",
                      help="Cloudera Manager admin user password")
    parser.add_option("--gateway", default=None,
                      help=("Gateway host to upload the data from. If not set, uses the "
                            "CM host as gateway."))
    parser.add_option("--ssh-user", default="jenkins",
                      help=("System user on the remote machine with passwordless "
                            "SSH configured."))
    parser.add_option("--no-load", action="store_false", default=True, dest="load",
                      help="Do not try to load the snapshot")
    parser.add_option("--exploration-strategy", default="core")
    parser.add_option("--test", action="store_true", default=False,
                      help="Run end-to-end tests against cluster")
    parser.set_usage("remote_data_load.py [options] cm_host")

    options, args = parser.parse_args()

    try:
        return options, args[0]  # args[0] is the cm_host
    except IndexError:
        logger.error("You must supply the cm_host.")
        parser.print_usage()
        raise
def main():
	parser = OptionParser(conflict_handler="resolve")
	parser.set_usage("mail-instance-creator.py <from-email-address> <to-email-address> <languagecode> <wikiaddress>\n\n\texample: mail-instance-creator.py '*****@*****.**' 'es' 'http://example.com/w/'")

	(options, args) = parser.parse_args()

	if len(args) != 4:
		parser.error("mail-instance-creator.py expects exactly four arguments.")

	fromaddress = args[0]
	toaddress = args[1]
	lang = args[2]
	wikiaddress = args[3]
	subjecturl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-subject/' + lang + '}}&format=xml'
	bodyurl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-body/' + lang + '}}&format=xml'
	dom = minidom.parse(urllib.urlopen(subjecturl))
	subject = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	dom = minidom.parse(urllib.urlopen(bodyurl))
	p = subprocess.Popen("ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub", shell=True, stdout=subprocess.PIPE)
	fingerprint = p.communicate()[0]
	fingerprint = fingerprint.split(' ')[1]
	body = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	body = body + ' ' + gethostname() + ' (' + fingerprint + ')'
	message = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (fromaddress, toaddress, subject, body)
	p = subprocess.Popen("/usr/sbin/sendmail -t", shell=True, stdin=subprocess.PIPE)
	p.communicate(message)
	if p.wait() != 0:
		return 1
Beispiel #14
0
def main():
    parser = OptionParser()
    parser.set_usage(_("Usage:  billreminder [OPTIONS...]"))
    parser.add_option('--version', action='store_true', dest='app_version', default=False, help=_('Displays the version number for this application.'))
    parser.add_option('--verbose', action='store_true', dest='app_verbose', default=False, help=_('Print output messages.'))
    parser.add_option('--no-daemon', action='store_true', dest='app_nodaemon', default=False, help=_("Don't run as a daemon."))
    parser.add_option('--open-gui', action='store_true', dest='app_opengui', default=False, help=_('Start daemon and launch GUI.'))
    parser.add_option('--stop', action='store_true', dest='app_stop', default=False, help=_('Stop daemon.'))

    # Verify arguments
    options, args = parser.parse_args()
    if options.app_stop:
        import dbus
        import dbus.service
        if verify_service(common.DBUS_INTERFACE):
            session_bus = dbus.SessionBus()
            obj = session_bus.get_object(common.DBUS_INTERFACE,
                                         common.DBUS_PATH)
            dbus_interface = dbus.Interface(obj, common.DBUS_INTERFACE)
            dbus_interface.quit()
    elif options.app_version:
        print _('This is %(appname)s - Version: %(version)s') % \
                         {'appname': _("BillReminder Notifier"),
                          'version': common.APPVERSION}
    else:
        BillReminderd.main(options)
Beispiel #15
0
def optParse():
    """
    Parses commandline options.
    """
    parser = OptionParser(
        prog=__applicationName__, version="%prog " + __version__)

    parser.set_usage("%prog [options] filename")
    parser.add_option("--autobrief",
                      action="store_true", dest="autobrief",
                      help="use the docstring summary line as @brief description"
                      )
    parser.add_option("--debug",
                      action="store_true", dest="debug",
                      help="enable debug output on stderr"
                      )

    # parse options
    global options
    (options, filename) = parser.parse_args()

    if not filename:
        sys.stderr.write("No filename given.")
        sys.exit(-1)

    return filename[0]
Beispiel #16
0
    def create_parser(self, prog_name, subcommand):
        parser = OptionParser(prog=prog_name, add_help_option=False,
                              formatter=SynnefoCommandFormatter())

        parser.set_usage(self.usage(subcommand))
        parser.version = self.get_version()

        # Handle Django's and common options
        common_options = OptionGroup(parser, "Common Options")
        common_options.add_option("-h", "--help", action="help",
                                  help="show this help message and exit")

        common_options.add_option("--version", action="version",
                                  help="show program's version number and"
                                       "  exit")
        [common_options.add_option(o) for o in self.option_list]
        if common_options.option_list:
            parser.add_option_group(common_options)

        # Handle command specific options
        command_options = OptionGroup(parser, "Command Specific Options")
        [command_options.add_option(o)
         for o in getattr(self, "command_option_list", ())]
        if command_options.option_list:
            parser.add_option_group(command_options)

        return parser
Beispiel #17
0
class Clone():
	def __init__(self):
		self.git = Git()
		self.parser = OptionParser()
		self.parser.add_option("-b", "--branch", dest="branch", help="with checkout branch")
		self.parser.add_option("-C", "--repo-dir", dest="repodir", help="repo directory")
		self.parser.add_option("-R", "--recursive", dest="recursive", help="clone project and subproject recursively")
		self.parser.set_usage("mgit clone <url> [-b <branch>]")

	def print_usage(self):
		self.parser.print_usage()
	
	def run(self, orig_args):
		options,args = self.parser.parse_args(orig_args)
		args = args[1:]
		if len(args) <= 0:
			self.print_usage()
			return
		project_dir = self.git.module_name(args[0])
		if project_dir == None or len(project_dir) <= 0:
			print("Unknow project name.Please use git clone, then use mgit sync in the project dir.")
			return
		cmd = ['git', 'clone'] + args
		if options.branch != None:
			cmd += ["-b", options.branch]
		if 0 != os.system(" ".join(cmd)):
			return
		cwd = os.getcwd()
		os.chdir("/".join([cwd, project_dir]))
		sync = Sync()
		sync.run(['sync'] + orig_args[1:])
		os.chdir(cwd)
Beispiel #18
0
def get_optparser():
    parser = OptionParser(epilog='version %s, http://github.com/shadowprince/ddcp/' % VERSION)
    parser.set_usage('ddcp SOURCE... DESTINATION')
    parser.add_option('-b', '--block-size', 
            default=DEFAULT_BS, 
            help='block size for dd\'s bs, default = %s' % DEFAULT_BS
            )

    parser.add_option('-q', '--quiet', 
            action='store_true', 
            help='dont print progress to stdout default = false'
            )
    parser.add_option('-d', '--detailed', 
            action='store_true', 
            help='detailed output (with bar), default = false'
            )
    parser.add_option('-v', '--verbose', 
            action='store_true', 
            help='print system messages instead of progress bar, default = false'
            )

    parser.add_option('-t', '--time-delay', 
            help='time delay between dd sessions, default = %s' % DEFAULT_TIME_DELAY, 
            default=DEFAULT_TIME_DELAY
            )

    parser.add_option('', '--test', 
            help='dont run dd command, default = false', action='store_true'
            )
    parser.add_option('', '--dd', 
            help='various dd arguments added to execution string, default = blank', 
            default=''
            )

    return parser
Beispiel #19
0
def parse_commandline():
    """Parse the comandline and return parsed options."""

    parser = OptionParser()
    parser.description = __doc__

    parser.set_usage('usage: %prog [options] (add|delete) [package].\n'
                     'Try %prog --help for details.')
    parser.add_option('-d', '--debug', action='store_true',
                      help='Enables debugging mode')
    parser.add_option('-l', '--login',
                      help='Username to login with')
    parser.add_option('-a', '--account',
                      help='User owning the repositories to be changed ' \
                           '[default: same as --login]')
    parser.add_option('-t', '--apitoken',
                      help='API Token - can be found on the lower right of ' \
                           'https://github.com/account')

    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error('wrong number of arguments')
    if (len(args) == 1 and args[0] in ['add', 'delete']):
        parser.error('%r needs a package name as second parameter\n' % args[0])
    if (len(args) == 2 and args[0] not in ['add', 'delete']):
        parser.error('unknown command %r. Try "add" or "delete"\n' % args[0])

    return options, args
Beispiel #20
0
def call_wiener(args):
    '''
Image restoration by Wiener filter.
Restauration d image par filtre de Wiener
wiener <mat_source_name> <mat_res_name>
    '''
    usage = 'wiener <mat_source_name> <mat_res_name>'
    prog  = 'wiener'
    desc  = call_wiener.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    src   = args[0]
    trg   = args[1]
    if not check_name(src):      return -1
    if not check_mat(src):       return -1
    if not check_overwrite(trg): return -1
    res = resto_wiener(WORLD[src][1])
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #21
0
  def __init__(self):
    usage = "--user <user-name> [--database <database-name>] [--host <host-name>] [--port <port>]"
    parser = OptionParser()
    parser.set_usage(usage)
    parser.add_option("-u", "--user", dest="user", help="DataHub username")
    parser.add_option("-H", "--host", dest="host", help="DataHub server hostname", default="datahub-experimental.csail.mit.edu")
    parser.add_option("-p", "--port", dest="port", help="DataHub server port", type="int", default=9000)
    parser.add_option("-d", "--database", dest="database", help="DataHub database")
    (self.options, self.arg_values) = parser.parse_args()

    if not self.options.user:
      parser.print_usage()
      sys.exit(1)

    parser.destroy()
    self.password = getpass.getpass('DataHub password for %s: ' %(self.options.user))
    cmd2.Cmd.__init__(self, completekey='tab')
    self.client = DataHubClient(host=self.options.host, port=self.options.port)
    try:
      database = None
      if self.options.database:
        database=DHDatabase(name=self.options.database)
      con_params = DHConnectionParams(
          user=self.options.user,
          password=self.password,
          database=database)
      self.con = self.client.connect(con_params)
      self.prompt = "datahub> "
    except Exception, e:
      self.print_line('error: %s' % (e.message))
      sys.exit(1)
Beispiel #22
0
def call_load_world(args):
    '''
Load a work space from a file.
Charge un espace de travial depuis un fichier.
    '''
    usage = 'load_world <file_name>\nload_world mydata.pck'
    prog  = 'load_world'
    desc  = call_load_world.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    fname = args[0]
    if not check_name_file(fname): return -1
    f = open(fname, 'r')
    try: local = cPickle.load(f)
    except:
        outbox_error('Can not open the file')
        f.close()
        return -1
    f.close()
    if local[0] != 'world_astir':
        outbox_error('Not Astir format')
        return -1
    answer = inbox_question('All variables will be deleted, are you agree')
    if answer == 'n': return 0
    del WORLD
    WORLD = local[1]

    return 1
Beispiel #23
0
def call_fun(args):
    '''
Listing funtions available in Astir
Liste les fonctions disponible dans Astir
    '''
    usage = 'fun'
    prog  = 'fun'
    desc  = call_fun.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-c', action='store', type='int', default='4', help='Number of columns. Nombre de colonnes')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) > 0:
        p.print_help()
        return 0
    listfun.sort()
    sfun = len(listfun)
    nc   = opt.c
    if sfun % nc == 0: nl = sfun // nc
    else:              nl = (sfun // nc) + 1
    smax = 0
    for i in xrange(sfun):
        val = len(listfun[i])
        if val > smax: smax = val
    for i in xrange(nl):
        txt = ''
        for j in xrange(nc):
            ind = j * nl + i
            if ind < sfun: txt += '%s  ' % listfun[ind].ljust(smax)
            else:          txt += ''
        print txt

    return 1
Beispiel #24
0
def call_div(args):
    '''
Divide two mat variables (L or RGB).
Divise deux variables mat (L ou RGB)
mat_c = mat_a / mat_b
    '''
    usage = 'div <mat_a> <mat_b> <mat_c>\n\
             div im1 im2 res\n'
    prog  = 'div'
    desc  = call_div.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 3:
        p.print_help()
        return 0
    src1, src2, trg = args
    if not check_name([src1, src2]): return -1
    if not check_mat([src1, src2]):  return -1
    if not check_overwrite(trg):     return 0
    mat1 = WORLD[src1][1]
    mat2 = WORLD[src2][1]
    res  = mat1 / mat2
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #25
0
def call_mem(args):
    '''
Memories used in work space by the variables
Mémoire utilisee dans les espaces de travails par les variables
    '''
    usage = 'mem'
    prog  = 'mem'
    desc  = call_mem.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) > 0:
        p.print_help()
        return 0
    space = 10
    txt = ['', 'k', 'M', 'G', 'T']
    nbb = {'float8':1, 'float16':2, 'float32':4, 'float64':8,
            'uint8':1,  'uint16':2,  'uint32':4,  'uint64':8}
    lname = WORLD.keys()
    for name in lname:
        size   = WORLD[name][1].size
        dtype  = WORLD[name][1].dtype
        size  *= nbb[dtype]
        ie     = int(log(size) // log(1e3))
        size  /= (1e3 ** ie)
        size   = '%5.2f %sB' % (size, txt[ie])
        print '%s %s%s %s%s%s' % (name.ljust(space), 
              G, kind.ljust(space), 
              R, size.ljust(space), N)
        
    return 1
Beispiel #26
0
def call_anaglyph(args):
    '''
Create an anaglyph image from two RGB matrix (right and left).
Creer une image anaglyphe depuis deux mat RGB (droite et gauche).
    '''
    usage = 'anaglyph <mat_right> <mat_left> [options]\n\
             anaglyph imr img -o newim\n'
    prog  = 'anaglyph'
    desc  = call_anaglyph.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-o', action='store', type='string', default='res_anag', help='Output name (default res_anag)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src1, src2 = args
    trg        = opt.o
    if not check_name([src1, src2]): return -1
    if not check_mat([src1, src2]):  return -1
    if not check_overwrite(trg):     return 0
    im1, im2 = WORLD[src1][1], WORLD[src2][1]
    if not check_RGB(im1): return -1
    if not check_RGB(im2): return -1
    res = image_anaglyph(im1, im2)
    WORLD[trg] = ['mat', res]
    
    return 1
Beispiel #27
0
def call_colormap(args):
    '''
Apply false-colors to a luminance mat.
Applique des fausses couleurs sur une mat en luminance
colormap <mat_name> <kind_of_map> <new_mat_name>
different color of map: jet, hsv, hot

colormap im1 hot im_map    
    '''
    usage = 'colormap <mat_name> <new_name> [options]\n\
             colormap im1 im1color -c jet'
    prog  = 'colormap'
    desc  = call_colormap.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-c', action='store', type='string', default='jet', help='Kind of colormap jet, hsv and hot (default is jet)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src, trg = args
    kind     = opt.c
    if not check_name(src):      return -1
    if not check_mat(src):       return -1
    if not check_overwrite(trg): return  0
    if not check_L(src):         return -1
    if kind not in ['jet', 'hsv', 'hot']:
        outbox_error('Kind of map color unknown')
        return -1
    res = color_colormap(WORLD[src][1], kind)
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #28
0
def call_save_world(args):
    '''
Save the whole work space to a file.
Sauvegarde entierement l espace de travail dans un fichier
    '''
    usage = 'save_world <file_name>\nsave_world backup.pck'
    prog  = 'save_world'
    desc  = call_save_world.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    kname = WORLD.keys()
    if len(kname) == 0:
        outbox_bang('Nothing to save')
        return 0
    fname = args[0]
    if not check_overwrite_file(fname): return -1
    f = open(fname, 'w')
    local = ['world_astir', WORLD]
    cPickle.dump(local, f, 1)
    f.close()
    
    return 1
Beispiel #29
0
def call_cut_seq(args):
    '''
Cut a part of sequence to a new one, start and stop
specifies the part you want keep. Coupe une partie d une 
sequence dans une nouvelle, start et stop specifis la partie
que vous voulez garder.
    '''
    usage = 'cut_seq <seq_name> <new_seq_name> [option]\n\
             cut_seq vid1 newvid -s 10 -e 34\n'
    prog  = 'cut_seq'
    desc  = call_cut_seq.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-s', action='store', type='int', default='-1', help='Start number (default 0)')
    p.add_option('-e', action='store', type='int', default='-1', help='Stop number (default until the end)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src, trg = args
    if not check_name(src):      return -1
    if not check_seq(src):       return -1
    if not check_overwrite(trg): return  0
    if opt.s == -1: opt.s = 0
    if opt.e == -1: opt.e = WORLD[src][1].shape[0]
    seq = []
    for n in xrange(opt.s, opt.e + 1):
        seq.append(WORLD[src][1][n])
    seq = array(seq)
    WORLD[trg] = ['seq', seq]
    del seq

    return 1
Beispiel #30
0
def call_show_mat(args):
    '''
Display a mat variable as an image.
Affiche une variable de type mat comme une image.
    '''
    usage = 'show_mat <mat_name>\nshow_mat <mat_name1> <mat_name2>'
    prog  = 'show_mat'
    desc  = call_show_mat.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) == 0 or len(args) > 2:
        p.print_help()
        return 0
 
    list_im = []
    if not check_name(args): return -1
    if not check_mat(args):  return -1    
    for name in args:
        im = WORLD[name][1]
        list_im.append(im)

    image_show(list_im)
    del list_im, args, im

    return 1
Beispiel #31
0
    def connect_to_server(self, server='localhost', port=10000):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Bind the socket to the port
        server_address = (server, port)
        self.sock.connect(server_address)
        print >> sys.stderr, 'connected to %s on port %s' % server_address
        self.logger.debug('connected to %s on port %s' % server_address)
        self.sock.send('hello')


if __name__ == "__main__":
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('gps_tracker.py -p <port>')
    p.set_description(__doc__)
    p.add_option('-p',
                 '--port',
                 dest='port',
                 type=int,
                 help='port on which to connect to server')
    p.add_option('-s',
                 '--server',
                 dest='server',
                 type=str,
                 help='target server')
    opts, args = p.parse_args(sys.argv[1:])

    tracker = GpsTrackerDeviceSimulator()
    tracker.connect_to_server(server='localhost', port=opts.port)
Beispiel #32
0
def cmd_tool():
    """ Command line utility for converting Sigproc filterbank (.fil) to  HDF5 (.h5) format

    Usage:
        fil2h5 <FULL_PATH_TO_FIL_FILE> [options]

    Options:
      -h, --help            show this help message and exit
      -o OUT_DIR, --out_dir=OUT_DIR
                            Location for output files. Default: local dir.
      -n NEW_FILENAME, --new_filename=NEW_FILENAME
                            New name. Default: replaces extention to .h5
      -d, --delete_input    This option deletes the input file after conversion.
      -l MAX_LOAD           Maximum data limit to load. Default:1GB
    """

    p = OptionParser()
    p.set_usage(
        'Command line utility for converting Sigproc filterbank (.fil) to  HDF5 (.h5) format  \n >>fil2h5 <FULL_PATH_TO_FIL_FILE> [options]'
    )
    p.add_option('-o',
                 '--out_dir',
                 dest='out_dir',
                 type='str',
                 default='./',
                 help='Location for output files. Default: local dir. ')
    p.add_option('-n',
                 '--new_filename',
                 dest='new_filename',
                 type='str',
                 default='',
                 help='New name. Default: replaces extention to .h5')
    p.add_option('-d',
                 '--delete_input',
                 dest='delete_input',
                 action='store_true',
                 default=False,
                 help='This option deletes the input file after conversion.')
    p.add_option('-l',
                 action='store',
                 default=None,
                 dest='max_load',
                 type=float,
                 help='Maximum data limit to load. Default:1GB')

    opts, args = p.parse_args(sys.argv[1:])

    if len(args) != 1:
        logger.info('Please specify a file name \nExiting.')
        sys.exit()
    else:
        filename = args[0]

    make_h5_file(filename,
                 out_dir=opts.out_dir,
                 new_filename=opts.new_filename,
                 max_load=opts.max_load)

    if opts.delete_input:
        logger.info("'Deleting input file: %s" % (filename))
        os.remove(filename)
Beispiel #33
0
def main():
    parser = OptionParser()
    parser.set_usage(parser.get_usage().strip() + USAGE)
    parser.add_option("--repo-name",
                      dest="repo_name",
                      help="repository name - e.g. nitime",
                      metavar="REPO_NAME")
    parser.add_option("--github-user",
                      dest="main_gh_user",
                      help="github username for main repo - e.g fperez",
                      metavar="MAIN_GH_USER")
    parser.add_option("--gitwash-url",
                      dest="gitwash_url",
                      help="URL to gitwash repository - default %s" %
                      GITWASH_CENTRAL,
                      default=GITWASH_CENTRAL,
                      metavar="GITWASH_URL")
    parser.add_option("--gitwash-branch",
                      dest="gitwash_branch",
                      help="branch in gitwash repository - default %s" %
                      GITWASH_BRANCH,
                      default=GITWASH_BRANCH,
                      metavar="GITWASH_BRANCH")
    parser.add_option("--source-suffix",
                      dest="source_suffix",
                      help="suffix of ReST source files - default '.rst'",
                      default='.rst',
                      metavar="SOURCE_SUFFIX")
    parser.add_option("--project-url",
                      dest="project_url",
                      help="URL for project web pages",
                      default=None,
                      metavar="PROJECT_URL")
    parser.add_option("--project-ml-url",
                      dest="project_ml_url",
                      help="URL for project mailing list",
                      default=None,
                      metavar="PROJECT_ML_URL")
    (options, args) = parser.parse_args()
    if len(args) < 2:
        parser.print_help()
        sys.exit()
    out_path, project_name = args
    if options.repo_name is None:
        options.repo_name = project_name
    if options.main_gh_user is None:
        options.main_gh_user = options.repo_name
    repo_path = clone_repo(options.gitwash_url, options.gitwash_branch)
    try:
        copy_replace(
            (('PROJECTNAME', project_name), ('REPONAME', options.repo_name),
             ('MAIN_GH_USER', options.main_gh_user)),
            repo_path,
            out_path,
            cp_globs=(pjoin('gitwash', '*'), ),
            rep_globs=('*.rst', ),
            renames=(('\.rst$', options.source_suffix), ))
        make_link_targets(project_name, options.main_gh_user,
                          options.repo_name,
                          pjoin(out_path, 'gitwash', 'known_projects.inc'),
                          pjoin(out_path, 'gitwash', 'this_project.inc'),
                          options.project_url, options.project_ml_url)
    finally:
        shutil.rmtree(repo_path)
Beispiel #34
0
def main():
    """ Main funtion for find_candidate scripts. """

    p = OptionParser()
    p.set_usage('python find_candidates.py [options]')
    #    p.add_option('-o', '--out_dir', dest='out_dir', type='str', default='', help='Location for output files. Default: local dir. ')
    p.add_option(
        '-n',
        '--number_files',
        dest='n_files',
        type='int',
        default=6,
        help=
        'Number of files to check for candidates, standard is 6, for an ABACAD config.'
    )
    p.add_option('-l',
                 '--list_dats',
                 dest='dat_file_list',
                 type='str',
                 default='out_dats.lst',
                 help='List of .dat files to run (without the path).')
    p.add_option('-L',
                 '--list_fils',
                 dest='fil_file_list',
                 type='str',
                 default='../processed_targets.lst',
                 help='List of .fil files to run (with the path).')
    p.add_option('-p',
                 '--plotting',
                 dest='plotting',
                 action='store_true',
                 default=False,
                 help='Boolean for plotting. Default False, use for True.')
    p.add_option(
        '-s',
        '--saving',
        dest='saving',
        action='store_true',
        default=False,
        help=
        'Boolean for saving plot and csv data. Default False, use for True.')
    p.add_option('-r',
                 '--SNR_cut',
                 dest='SNR_cut',
                 type='int',
                 default=10,
                 help='SNR cut, default SNR=10.')
    p.add_option(
        '-z',
        '--check_zero_drift',
        dest='check_zero_drift',
        action='store_true',
        default=False,
        help=
        'Boolean for not ignoring zero drift hits, if True it will search them if only present in the ON. Default False, use for True.'
    )
    p.add_option(
        '-f',
        '--filter_threshold',
        dest='filter_threshold',
        type='int',
        default=3,
        help=
        'Filter_threshold allows the return of a table of candidates with hits at different levels of filtering.'
    )

    opts, args = p.parse_args(sys.argv[1:])

    #    out_dir = opts.out_dir
    n_files = opts.n_files
    dat_file_list = opts.dat_file_list
    fil_file_list = opts.fil_file_list
    plotting = opts.plotting
    saving = opts.saving
    SNR_cut = opts.SNR_cut
    check_zero_drift = opts.check_zero_drift
    filter_threshold = opts.filter_threshold

    #---------------------

    local_host = socket.gethostname()

    #Opening list of files
    dat_file_list = open(dat_file_list).readlines()
    dat_file_list = [files.replace('\n', '') for files in dat_file_list]

    #Check
    if len(dat_file_list) < n_files:
        print(
            "It seems len(dat_file_list) < n_files assuming len(dat_file_list) = n_files."
        )
        n_files = len(dat_file_list)

    #---------------------
    #Finding candidates.

    #Looping over n_files chunks.
    for i in range(len(dat_file_list) / n_files):

        file_sublist = dat_file_list[n_files * i:n_files * (i + 1)]

        candidates = find_candidates(file_sublist,
                                     SNR_cut=SNR_cut,
                                     check_zero_drift=check_zero_drift,
                                     filter_threshold=filter_threshold)

        #Saving csv
        if not candidates.empty and saving:
            candidates.to_csv('Candidates_%s.t%.0f.csv' %
                              (candidates['Source'].unique()[0],
                               float(candidates['MJD'].unique()[0])))

        #Plotting individual candidates
        if not candidates.empty and plotting:
            filenames = open(fil_file_list)
            filenames = filenames.readlines()
            filenames = [files.replace('\n', '') for files in filenames]

            #Choosing only a few candidates when having too many.
            A1_candidates = candidates[candidates['status'] ==
                                       'A1_table'].sort_values(by='SNR')
            candidate_index = A1_candidates['FreqEnd'].index.unique()[-5:]

            for ii in candidate_index:

                try:
                    Freq_Start = candidates['FreqStart'][ii].unique()[0]
                    Freq_End = candidates['FreqEnd'][ii].unique()[0]
                except:
                    Freq_Start = candidates['FreqStart'][ii]
                    Freq_End = candidates['FreqEnd'][ii]

                plot_candidates.make_waterfall_plots(
                    filenames[n_files * i:n_files * (i + 1)],
                    candidates['Source'].unique()[0],
                    Freq_Start,
                    Freq_End,
                    save_pdf_plot=saving,
                    saving_fig=saving,
                    local_host=local_host)
Beispiel #35
0
    dest="vehicle_types",
    help="vehicle-types for which the values shall be generated",
    metavar="<VEHICLE_TYPE>[,<VEHICLE_TYPE>]",
    type="string")
optParser.add_option(
    "-i",
    "--intervals",
    dest="interval",
    help="intervals to be generated ([0:<TIME>-1], [<TIME>:2*<TIME>-1], ...)",
    metavar="<TIME>",
    type="int")

optParser.set_usage(
    '\ngenerateITetrisNetworkMetrics.py -n inputs\\a_costa\\acosta.net.xml -p outputs\\a_costa\\ -t passenger2a,passenger5,passenger1,passenger2b,passenger3,passenger4 -i 500 \n'
    +
    'generateITetrisNetworkMetrics.py -n inputs\\a_costa\\acosta.net.xml -p outputs\\a_costa\\ -i 500\n'
    +
    'generateITetrisNetworkMetrics.py -n inputs\\a_costa\\acosta.net.xml -p outputs\\a_costa\\'
)
# parse options
(options, args) = optParser.parse_args()
if not options.netfile or not options.path:
    print "Missing arguments"
    optParser.print_help()
    exit()

interval = options.interval
netfile = options.netfile
vehroutefile = os.path.join(options.path, 'vehroutes.xml')

if interval == None:
def main():
    parser = OptionParser(conflict_handler="resolve")
    parser.set_usage("puppetsigner [options]")
    ldapSupportLib = ldapsupportlib.LDAPSupportLib()
    ldapSupportLib.addParserOptions(parser)
    (options, args) = parser.parse_args()
    ldapSupportLib.setBindInfoByOptions(options, parser)
    ds = ldapSupportLib.connect()
    try:
        proc = subprocess.Popen('/usr/sbin/puppetca -l',
                                shell=True,
                                stdout=subprocess.PIPE)
        hosts = proc.communicate()
        hosts = hosts[0].split()
        for host in hosts:
            if host[0] == "(":
                continue
            host = host.strip('"')
            basedn = getPuppetInfo('ldapbase')
            query = "(&(objectclass=puppetclient)(|(dc=" + host + ")(cnamerecord=" + host + ")(associateddomain=" + host + ")))"
            PosixData = ds.search_s(basedn, ldap.SCOPE_SUBTREE, query)
            if not PosixData:
                path = getPuppetInfo(
                    'ssldir') + '/ca/requests/' + host + '.pem'
                try:
                    os.remove(path)
                except Exception:
                    sys.stderr.write('Failed to remove the certificate: ' +
                                     path + '\n')
            else:
                subprocess.Popen(['/usr/sbin/puppetca -s ' + host],
                                 shell=True,
                                 stderr=subprocess.PIPE)
                subprocess.Popen([
                    '/usr/bin/php /srv/org/wikimedia/controller/wikis/w/extensions/OpenStackManager/maintenance/onInstanceActionCompletion.php --action=build --instance='
                    + host
                ],
                                 shell=True,
                                 stderr=subprocess.PIPE)
        proc = subprocess.Popen(
            '/usr/bin/salt-key --list=unaccepted --out=json',
            shell=True,
            stdout=subprocess.PIPE)
        hosts = proc.communicate()
        hosts = json.loads(hosts[0])
        for host in hosts["minions_pre"]:
            basedn = getPuppetInfo('ldapbase')
            query = "(&(objectclass=puppetclient)(|(dc=" + host + ")(cnamerecord=" + host + ")(associateddomain=" + host + ")))"
            PosixData = ds.search_s(basedn, ldap.SCOPE_SUBTREE, query)
            if not PosixData:
                subprocess.Popen(['/usr/bin/salt-key -y -d ' + host],
                                 shell=True,
                                 stdout=subprocess.PIPE)
            else:
                subprocess.Popen(['/usr/bin/salt-key -y -a ' + host],
                                 shell=True,
                                 stderr=subprocess.PIPE)
    except ldap.PROTOCOL_ERROR:
        sys.stderr.write("There was an LDAP protocol error; see traceback.\n")
        traceback.print_exc(file=sys.stderr)
        ds.unbind()
        sys.exit(1)
    except Exception:
        try:
            sys.stderr.write(
                "There was a general error, this is unexpected; see traceback.\n"
            )
            traceback.print_exc(file=sys.stderr)
            ds.unbind()
        except Exception:
            sys.stderr.write("Also failed to unbind.\n")
            traceback.print_exc(file=sys.stderr)
        sys.exit(1)

    ds.unbind()
    sys.exit(0)
Beispiel #37
0
class YamlOptions:
    "YamlOptions"

    def __init__(self, target):
        """
        Scan the class doc string of the given object, looking for the %YAML
        containing the option specification.  Parse the YAML and setup the
        corresponding OptionParser object.
        """
        # target - options object (input)
        # gname  - option group name

        self.y = get_yaml(target.__class__)
        self.parser = OptionParser(description=self.y['Description'],
                                   version='%prog version $Revision$')
        self.parser.remove_option('-h')
        self.parser.set_usage(self.y['Usage'])
        self.opty = self.y['Options']
        for gname in self.opty.get('Groups', []):
            self._register_group(gname)

    def _register_group(self, gname):
        """
        Register options for the specified option group name to the OptionParser
        using an OptionGroup unless the group name starts with 'Help' in which
        case we just register the options with the top level OptionParser object.
        """
        # gname    - option group name (input)
        # gy       - option group YAML object
        # grp      - option group object
        # tgt      - where to add options (parser or option group)
        # optkey   - comma separated list of option flags
        # optval   - help string or dict with detailed option settings
        # listargs - list of option flags (e.g. ['-h', '--help'])
        # dictargs - key/value arguments to add_option

        gy = self.opty.get(gname, None)
        if gname.startswith('Help'):
            grp = None
            tgt = self.parser
        else:
            grp = OptionGroup(self.parser, gname)
            tgt = grp

        for optkey, optval in gy.items():
            listargs = optkey.split(',')
            if type(optval) == type(''):
                # short form: optval is just a help string
                dictargs = {'action': 'store_true', 'help': optval}
            else:
                # optval is the complete option specification
                dictargs = optval

            # hide hidden options
            if dictargs.get('help', '').startswith('hidden'):
                dictargs['help'] = SUPPRESS_HELP

            #print 'adding', listargs, dictargs
            tgt.add_option(*listargs, **dictargs)

        if grp is not None:
            self.parser.add_option_group(grp)
Beispiel #38
0
            print ' Retries remaining: %i' % opts.n_retries


def check():
    if ((check_loopback_mcnt() != 0) or (check_xaui_error() != 0)
            or (check_x_miss() != 0)):
        return False
    else:
        return True


if __name__ == '__main__':
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('init_corr.py [options] CONFIG_FILE')
    p.set_description(__doc__)
    p.add_option('-m',
                 '--monitor_only',
                 dest='monitor_only',
                 action='store_true',
                 default=False,
                 help='Skip the initialision. ie Only monitor.')
    p.add_option(
        '-t',
        '--init_time',
        dest='init_time',
        action='store_true',
        default=False,
        help=
        'Set the BEEs time from the timeserver specified in the config file.  Default: do not set time'
Beispiel #39
0
#!/usr/bin/env python

import os, sys
import numpy as np

import simsio

#import matplotlib
#matplotlib.use('Agg')
#import pylab as p
#matplotlib.rc('xtick',labelsize=25)
#matplotlib.rc('ytick',labelsize=25)

if __name__ == "__main__":
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] [RMS txt files]')
    o.set_description(__doc__)
    opts, args = o.parse_args(sys.argv[1:])

    rmsFiles = args
    if rmsFiles[0] == 'RMS.dat':
        rmsDict = simsio.loadTotalRMSDat(rmsFiles[0])
    elif rmsFiles[0] == 'RMS.pkl':
        rmsDict = simsio.loadTotalRMSPkl(rmsFiles[0])
    else:
        rmsDict = simsio.rmsFromTxt(rmsFiles)
    print rmsDict
	def run(self):
		parser = OptionParser(conflict_handler="resolve")
		parser.set_usage("homedirectorymanager.py [options]\n\nexample: homedirectorymanager.py --dry-run")

		ldapSupportLib = ldapsupportlib.LDAPSupportLib()
		ldapSupportLib.addParserOptions(parser)

		parser.add_option("--dry-run", action="store_true", dest="dryRun", help="Show what would be done, but don't actually do anything")
		parser.add_option("--debug", action="store_true", dest="debugStatus", help="Run in debug mode (you likely want to use --dry-run with this)")
		(self.options, args) = parser.parse_args()

		self.dryRun = self.options.dryRun
		self.debugStatus = self.options.debugStatus

		# use proxy agent by default
		ldapSupportLib.setBindInfoByOptions(self.options, parser)

		base = ldapSupportLib.getBase()

		ds = ldapSupportLib.connect()
		self.logDebug("Connected")

		# w00t We're in!
		try:
			# get all user's uids
			UsersData = ldapSupportLib.getUsers(ds, '*')
			self.logDebug("Pulled the user information")

			# We are going to use a dictionary (associative array) as a hash bucket (keys pointing to dictionaries)
			# for the AllUsers data structure.
			# The data structure will look like this:
			# {"<uid>": {"uidNumber": <uidNumber>, "gidNumber": <gidNumber>, "sshPublicKey": ['key1', 'key2']}, 
			#  "<uid>": {"uidNumber": <uidNumber>, "gidNumber": <gidNumber>, "sshPublicKey": ['key1', 'key2']}}
			AllUsers = {}
			for user in UsersData:
				uid = user[1]['uid'][0]
				if 'uidNumber' not in user[1].keys():
					continue
				if 'gidNumber' not in user[1].keys():
					continue
				if 'sshPublicKey' not in user[1].keys():
					continue
				# uidNumber and gidNumber come back from LDAP as strings, we need ints here.
				uidNumber = int(user[1]['uidNumber'][0])
				gidNumber = int(user[1]['gidNumber'][0])
				sshPublicKey = user[1]['sshPublicKey']

				AllUsers[uid] = {}
				AllUsers[uid]["uidNumber"] = uidNumber
				AllUsers[uid]["gidNumber"] = gidNumber
				AllUsers[uid]["sshPublicKey"] = sshPublicKey

			self.changeGid(AllUsers)
			self.changeUid(AllUsers)
			self.moveUsers(AllUsers)
			self.createHomeDir(AllUsers)

		except ldap.UNWILLING_TO_PERFORM, msg:
			sys.stderr.write("The search returned an error. Error was: %s\n" % msg[0]["info"])
			ds.unbind()
			sys.exit(1)
    exit()


def exit_clean():
    try:
        c.disconnect_all()
    except:
        pass
    exit()


if __name__ == '__main__':
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('rst_errors.py CONFIG_FILE')
    p.set_description(__doc__)
    p.add_option(
        '-r',
        '--n_retries',
        dest='n_retries',
        type='int',
        default=-1,
        help=
        'Number of times to try after an error before giving up. Set to -1 for infinity. Default: -1'
    )
    p.add_option('-v',
                 '--verbose',
                 dest='verbose',
                 action='store_true',
                 default=False,
Beispiel #42
0
def HandleCommandLine(params,
                      argv=None,
                      conf_module_name=None,
                      default_arg="install",
                      opt_parser=None,
                      custom_arg_handlers={}):
    """Perform installation or removal of an ISAPI filter or extension.
    
    This module handles standard command-line options and configuration
    information, and installs, removes or updates the configuration of an
    ISAPI filter or extension.
    
    You must pass your configuration information in params - all other
    arguments are optional, and allow you to configure the installation
    process.
    """
    global verbose
    from optparse import OptionParser

    argv = argv or sys.argv
    if not conf_module_name:
        conf_module_name = sys.argv[0]
        # convert to a long name so that if we were somehow registered with
        # the "short" version but unregistered with the "long" version we
        # still work (that will depend on exactly how the installer was
        # started)
        try:
            conf_module_name = win32api.GetLongPathName(conf_module_name)
        except win32api.error as exc:
            log(
                2, "Couldn't determine the long name for %r: %s" %
                (conf_module_name, exc))

    if opt_parser is None:
        # Build our own parser.
        parser = OptionParser(usage='')
    else:
        # The caller is providing their own filter, presumably with their
        # own options all setup.
        parser = opt_parser

    # build a usage string if we don't have one.
    if not parser.get_usage():
        all_handlers = standard_arguments.copy()
        all_handlers.update(custom_arg_handlers)
        parser.set_usage(build_usage(all_handlers))

    # allow the user to use uninstall as a synonym for remove if it wasn't
    #  defined by the custom arg handlers.
    all_handlers.setdefault('uninstall', all_handlers['remove'])

    parser.add_option("-q",
                      "--quiet",
                      action="store_false",
                      dest="verbose",
                      default=True,
                      help="don't print status messages to stdout")
    parser.add_option("-v",
                      "--verbosity",
                      action="count",
                      dest="verbose",
                      default=1,
                      help="increase the verbosity of status messages")
    parser.add_option("", "--server", action="store",
                      help="Specifies the IIS server to install/uninstall on." \
                           " Default is '%s/1'" % (_IIS_OBJECT,))

    (options, args) = parser.parse_args(argv[1:])
    MergeStandardOptions(options, params)
    verbose = options.verbose
    if not args:
        args = [default_arg]
    try:
        for arg in args:
            handler = all_handlers[arg]
            handler(conf_module_name, params, options, log)
    except (ItemNotFound, InstallationError) as details:
        if options.verbose > 1:
            traceback.print_exc()
        print("%s: %s" % (details.__class__.__name__, details))
    except KeyError:
        parser.error("Invalid arg '%s'" % arg)
Beispiel #43
0
import corr
import iadc
import time
import struct
import pylab
from optparse import OptionParser
import sys, os
import numpy as np

p = OptionParser()
p.set_usage(
    'python plot_adcs.py <specify IP address of the snap-pi, specify the boffile>'
)
p.set_description(__doc__)
p.add_option('-i',
             '--ip',
             dest='ip',
             type='str',
             default='',
             help='IP address of the raspberry pi')
p.add_option('-b',
             '--bof',
             dest='boffile',
             type='str',
             default='extadc_snap_spec_2017-03-24_1035.bof',
             help='Specify the bof file to load')
opts, args = p.parse_args(sys.argv[1:])

SNAPHOST = opts.ip
BOFFILE = opts.boffile
Beispiel #44
0
parser.add_option(
    "-a",
    "--auto-name",
    dest="auto_name",
    action="store_true",
    default=False,
    help=
    "Auto name the mesh file: mesh_dim1_dim2[_dim3].bin. Default requires a name"
)

progName = sys.argv[0]
usage = progName + " MESH_FILE DIM1 DIM2 [DIM3]\n"
usage += "\t-- OR --\n"
usage += "\t" + progName + " -a DIM1 DIM2 [DIM3]"

parser.set_usage(usage)

(options, args) = parser.parse_args()

conf = confLoader.ConfLoader(options.conf_file)

autoName = options.auto_name
dataType = conf.getDataType()
valsPerPoint = conf.getValuesPerPoint()

dims = []

if len(args) < 1 and not autoName:
    print "You must specify a filename for the mesh or use Auto-Naming!"
    parser.print_usage()
    sys.exit(1)
Beispiel #45
0
                2, "Couldn't determine the long name for %r: %s" %
                (conf_module_name, exc))

    if opt_parser is None:
        # Build our own parser.
        parser = OptionParser(usage='')
    else:
        # The caller is providing their own filter, presumably with their
        # own options all setup.
        parser = opt_parser

    # build a usage string if we don't have one.
    if not parser.get_usage():
        all_handlers = standard_arguments.copy()
        all_handlers.update(custom_arg_handlers)
        parser.set_usage(build_usage(all_handlers))

    # allow the user to use uninstall as a synonym for remove if it wasn't
    #  defined by the custom arg handlers.
    all_handlers.setdefault('uninstall', all_handlers['remove'])

    parser.add_option("-q",
                      "--quiet",
                      action="store_false",
                      dest="verbose",
                      default=True,
                      help="don't print status messages to stdout")
    parser.add_option("-v",
                      "--verbosity",
                      action="count",
                      dest="verbose",
Beispiel #46
0
	return failed

if __name__=='__main__':
	import sys
	from optparse import OptionParser
	op=OptionParser()
	op.add_option("-d", "--debug", action="store_true", default=False,
				help="detailed debug output of objects that don't match")
	op.add_option("-f", "--failures", action="store_true", default=False,
				help="show only failures")
	op.add_option("-m", "--missing", action="store_true", default=False,
				help="show only missing tests")
	op.add_option("-t", "--tolerance", action="store", default=None,
	              help="tolerance used to estimate accuracy")

	op.set_usage("[<file1> <file2> ...]")
	(opts, args)=op.parse_args()
	if opts.debug:
		cmp_method=compare_dbg
	else:
		cmp_method=compare
	tests = setup_tests(args)
	failed = tester(tests, cmp_method, opts.tolerance, opts.failures, opts.missing)
	if failed:
		print
		print "The following tests failed!"
		for f in failed:
			print "\t", f
		sys.exit(1)
	sys.exit(0)
Beispiel #47
0
    return crosses


def parse_range(range):
    """Parse *range*, which should look like -35.7354:25.1. Return (lower, upper)."""
    l = range.split(':')
    return (float(l[0]), float(l[1]))


if __name__ == '__main__':
    from optparse import OptionParser

    # Set up and handle command line arguments
    parser = OptionParser()
    parser.set_usage(
        "usage: %prog [options] <start YYMMDD> <end YYMMDD> satellite1 [satellite2 [...]]\n"
        "Find times and locations where Calipso and the specified satellites cross paths."
    )
    parser.add_option('-t',
                      '--time_window',
                      type='int',
                      default=20,
                      help="Time window for crossing. Default: 20 min.")
    parser.add_option(
        '-x',
        '--longitudes',
        type='string',
        help="Range of acceptable longitudes (e.g. -35.7:25.12).")
    parser.add_option('-y',
                      '--latitudes',
                      type='string',
                      help="Range of acceptable latitudes (e.g. -35.7:25.12).")
    type="string",
    default="./")
optParser.add_option("-o",
                     "--harmonoiseFile",
                     dest="harmonoiseFile",
                     help="name of the harmonoise file",
                     metavar="<FOLDER>",
                     type="string")
optParser.add_option("-e",
                     "--HBEFAFile",
                     dest="hbefaFile",
                     help="name of the HBEFA file",
                     metavar="<FOLDER>",
                     type="string")

optParser.set_usage(
    '\n-n inputs\\pasubio\\pasubio.net.xml -p inputs\\pasubio\\')
# parse options
(options, args) = optParser.parse_args()
if not options.netfile:
    print "Missing arguments"
    optParser.print_help()
    exit()

netfile = options.netfile
e2OutputFile = os.path.join(options.path, 'e2_output.xml')

net = sumolib.net.readNet(netfile)

e2Output = E2OutputReader()
parse(e2OutputFile, e2Output)
"""

import os, sys
import shutil
import subprocess
import glob
import datetime

SCRIPT_DIR = '/home/artemis/Survey/Scripts/'  # HARDCODE, see --script_dir option
ABC3_DIR = '/databk/datProcessing/'  # HARDCODE, see --abc3 option
GENERATOR_SCRIPT = 'generateDedispFigures.py'

if __name__ == '__main__':
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] INPUT_DIR PROC_DIR OUTPUT_DIR')
    o.add_option(
        '-S',
        '--script_dir',
        dest='scriptDir',
        default=SCRIPT_DIR,
        help='Directory of scripts (generateDedispFigures.py), default: %s' %
        SCRIPT_DIR)
    o.add_option('--abc3',
                 dest='abc3Dir',
                 default=ABC3_DIR,
                 help='Directory on ABC3 to store DAT files, default: %s' %
                 ABC3_DIR)
    o.add_option(
        '--run',
        dest='run',
    return output_root


#### Command line main

if __name__ == '__main__':

    # Set up command line interface.
    parser = OptionParser(description='''\
This script can install, uninstall, validate an installation, and create
packages for VoltDB. It uses the working directory to determine the active
source tree. When creating a package it detects whether the source tree is for
the pro or the community edition and adjusts the package accordingly. If a
distribution tarball is provided this script uses the distribution tree from
that tarball instead of the working directory.''')
    parser.set_usage('%prog [OPTIONS] [DISTRIBUTION_TARBALL]')
    parser.add_option('-C',
                      '--clean',
                      action='store_true',
                      dest='clean',
                      help='clean package building output')
    parser.add_option('-c',
                      '--check',
                      action='store_true',
                      dest='check',
                      help='check VoltDB installation')
    parser.add_option('-D',
                      '--debian',
                      action='store_true',
                      dest='debian',
                      help='create debian package')
Beispiel #51
0
#!/usr/bin/env python
"""
Save a HEALPIX FITS map
"""

import sys, os
import numpy as n

import healpy as h

if __name__ == '__main__':
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] FITS_MAPS')
    o.set_description(__doc__)
    o.add_option('-s',
                 '--save',
                 dest='savemap',
                 default=None,
                 help='Save map to file')
    opts, args = o.parse_args(sys.argv[1:])

    m = None
    w = None
    for fn in args:
        print 'Opening:', fn
        if m is None: m, w, hdr = h.read_map(fn, field=(0, 1), h=True)
        else:
            m0, w0, hdr = h.read_map(fn, field=(0, 1), h=True)
            m += m0
            w += w0
Beispiel #52
0
#! /usr/bin/env python
"""
Reads the error counters on the correlator and reports accumulated XAUI and
packet errors.
"""
import corr, time, sys, struct

if __name__ == '__main__':
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('read_missing.py [options] CONFIG_FILE')
    p.set_description(__doc__)
    opts, args = p.parse_args(sys.argv[1:])

    if args == []:
        print 'Please specify a configuration file! \nExiting.'
        exit()

    config = corr.cn_conf.CorrConf(args[0])
    config_status = config.read_all()
    print '\n\nParsing config file %s...%s' % (args[0], config_status)
    sys.stdout.flush()
    if not config_status == 'OK': exit()

servers = [s['server'] for s in config['servers']]
fpgas = [
    corr.udp_client.UDPClient(s['server'], s['port'])
    for s in config['servers']
]
n_xeng_per_fpga = config['x_per_fpga']
Beispiel #53
0
import errno
import os
from optparse import OptionParser
from lib.galago import GalagoRank

if __name__ == '__main__':
    parser = OptionParser(description='Generate a ranking using Galago')
    parser.set_usage(parser.get_usage().replace('\n', '') + ' <xml_file_input>')
    parser.add_option('-g', '--galago', dest="galago_bin", default='/media/erikaris/DATA/ODU/Semester_3/intro_to_info_retrieval/galago/galago-3.10-bin/bin/galago',
                        help='Galago "home" directory')
    parser.add_option('-d', '--document', dest="document_dir", default='/media/erikaris/DATA/ODU/Semester_3/intro_to_info_retrieval/assignments/a4/code-report/cacm',
                        help='Document directory to be indexed')
    parser.add_option('-j', '--judgements', dest="judgements_file", default='/media/erikaris/DATA/ODU/Semester_3/intro_to_info_retrieval/assignments/a4/code-report/cacm.rel',
                      help='File .rel as galago eval judgments')
    parser.add_option('-r', '--result', dest="result_count", default='10', help='Number of result')

    (options, args) = parser.parse_args()
    options = vars(options)

    if len(args) < 1:
        parser.print_help()
        exit()


    out_dir = os.path.abspath('output')

    try: os.makedirs(out_dir)
    except OSError, e:
        if e.errno != errno.EEXIST: raise

    index_dir = os.path.join(os.path.pardir, 'index')
    l = h5file['bls_ordering'].value[0][baseline].tolist()
    return (l[0], l[1])


def tuple_to_baseline(h5file, t):
    for n, b in enumerate(h5file['bls_ordering'].value[0]):
        l = b.tolist()
        if t == (l[0], l[1]):
            return n
    return -1


if __name__ == '__main__':
    from optparse import OptionParser
    p = OptionParser()
    p.set_usage('%prog [options] [CUSTOM_CONFIG_FILE]')
    p.set_description(__doc__)
    p.add_option('',
                 '--noplot',
                 dest='noplot',
                 action='store_true',
                 default=False,
                 help='Do not plot.')
    p.add_option(
        '',
        '--plotonly',
        dest='plotonly',
        action='store_true',
        default=False,
        help='Plot only using exisintg data in the current directory.')
    p.add_option(
import pylab as p

import cPickle as pkl

matplotlib.rc('xtick', labelsize=25)
matplotlib.rc('ytick', labelsize=25)

modeTitle = [
    'Total Intensity', 'Invariant Interval', 'Matrix Template Matching'
]
fs = 27  #fontsize

if __name__ == "__main__":
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] [pklReduceDict.py DICT]')
    o.set_description(__doc__)
    o.add_option('-c',
                 '--cal',
                 dest='calMode',
                 default='cal',
                 help='cal mode to use: cal or uncal, default: cal')
    o.add_option(
        '-g',
        '--grid',
        dest='grid',
        default='0,3000,0,40',
        help=
        'Grid limits for the plot: SNR min , SNR max , IXR min (dB), IXR max (dB) default: 0,3000,0,40 '
    )
    o.add_option('-m',
Beispiel #56
0
	matplotlib.pyplot.clf()
	acc_n, interleave_a = get_data()
	
	f.write(interleave_a)
	f.



#START OF MAIN:

if __name__ == '__main__':
    from optparse import OptionParser


    p = OptionParser()
    p.set_usage('spectrometer.py <ROACH_HOSTNAME_or_IP> [options]')
    p.set_description(__doc__)
    p.add_option('-l', '--acc_len', dest='acc_len', type='int',default=2*(2**28)/2048,
        help='Set the number of vectors to accumulate between dumps. default is 2*(2^28)/2048, or just under 2 seconds.')
    p.add_option('-g', '--gain', dest='gain', type='int',default=0xffffffff,
        help='Set the digital gain (6bit quantisation scalar). Default is 0xffffffff (max), good for wideband noise. Set lower for CW tones.')
    p.add_option('-s', '--skip', dest='skip', action='store_true',
        help='Skip reprogramming the FPGA and configuring EQ.')
    p.add_option('-b', '--bof', dest='boffile',type='str', default='',
        help='Specify the bof file to load')
    opts, args = p.parse_args(sys.argv[1:])

    if args==[]:
        print 'Please specify a ROACH board. Run with the -h flag to see all options.\nExiting.'
        exit()
    else:
Beispiel #57
0
                            np.sum(np.sum(data, axis=1) / nchans) / nsamp))

            sys.stdout.write("===== Processing %d of %d [%.2f%%]   \r" %
                             (i, iterations, (i / float(iterations) * 100)))
            sys.stdout.flush()

        # Close files
        f.close()
        w.flush()
        w.close()


if __name__ == "__main__":

    p = OptionParser()
    p.set_usage('process_beams.py [options] INPUT_FILE')
    p.set_description(__doc__)

    p.add_option('-f',
                 '--bandpass',
                 dest='bandpass',
                 action='store_true',
                 default=False,
                 help='Show bandpass plots')
    p.add_option('-w',
                 '--waterfall',
                 dest='waterfall',
                 action='store_true',
                 default=False,
                 help='Show beam waterfall plots')
    p.add_option('-t',
Beispiel #58
0
        def __init__(self, banner, *argv, **argd):
            self.banner = banner
            IndentedHelpFormatter.__init__(self, *argv, **argd)

        def format_usage(self, usage):
            msg = IndentedHelpFormatter.format_usage(self, usage)
            return '%s\n%s' % (self.banner, msg)

    # Parse the command line arguments.
    formatter = BannerHelpFormatter(
        "Python script to use the Google search engine\n"
        "By Mario Vilas (mvilas at gmail dot com)\n"
        "https://github.com/MarioVilas/google\n")
    parser = OptionParser(formatter=formatter)
    parser.set_usage("%prog [options] query")
    parser.add_option("--tld",
                      metavar="TLD",
                      type="string",
                      default="com",
                      help="top level domain to use [default: com]")
    parser.add_option(
        "--lang",
        metavar="LANGUAGE",
        type="string",
        default="en",
        help="produce results in the given language [default: en]")
    parser.add_option("--num",
                      metavar="NUMBER",
                      type="int",
                      default=10,
Beispiel #59
0
if __name__ == '__main__':
    import ConfigParser
    import logging
    import sys
    from optparse import OptionParser

    logging.basicConfig()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    parser = OptionParser()
    parser.set_usage("""
    usage: %prog [options]

    --s3-upload-bucket, --aws-access-key-id, --aws-access-key must be specified
    together either as command line options or in the --config file.

    --upload and --key must be specified together.
    """)
    parser.add_option('--s3-upload-bucket',
                      dest='s3_upload_bucket',
                      action='store',
                      type='string',
                      default=None,
                      help="""AWS S3 bucket name used to store logs.
                      Defaults to None. If specified, --aws-access-key-id
                      and --aws-secret-access-key must also be specified.
                      """)
    parser.add_option('--aws-access-key-id',
                      dest='aws_access_key_id',
                      action='store',
Beispiel #60
0
def main():

    p = OptionParser()
    p.set_usage('python seti_event.py <FULL_PATH_TO_FIL_FILE> [options]')

    #    p.add_option('-m', '--min_drift', dest='min_drift', type='float', default=0.0, help='Set the minimum drift rate to search. Unit: Hz/sec. Default:0.0')
    p.add_option(
        '-M',
        '--max_drift',
        dest='max_drift',
        type='float',
        default=10.0,
        help='Set the drift rate to search. Unit: Hz/sec. Default: 10.0')
    p.add_option('-s',
                 '--snr',
                 dest='snr',
                 type='float',
                 default=25.0,
                 help='SNR threshold. Default: 25.0')
    #    p.add_option('-b', '--bw', dest='bw', type='float', default=1, help='Specify the amount of \'compression\' to be done in frequency domain to search for more \'spread out\' signals. Unit:?. Default: ?')
    p.add_option('-o',
                 '--out_dir',
                 dest='out_dir',
                 type='str',
                 default='./',
                 help='Location for output files. Default: local dir. ')
    #    p.add_option('-w', '--width', dest='slice_width', type='int', default=512, help='')
    p.add_option('-l',
                 '--loglevel',
                 dest='loglevel',
                 type='str',
                 default='info',
                 help='Specify log level (info, debug)')
    p.add_option(
        '-c',
        '--coarse_chans',
        dest='coarse_chans',
        type='str',
        action='callback',
        default='',
        callback=make_list,
        help=
        'Coma separated list of coarse channels to analyze.(ie. "5,8" to do from 5th to 8th coarse channels)'
    )
    opts, args = p.parse_args(sys.argv[1:])

    if len(args) != 1:
        print('Please specify a file name \nExiting.')
        sys.exit()
    else:
        filename = args[0]

    # Stuff needed for LOFAR version. will remove
    obs_info = {}
    obs_info['pulsar'] = 0  # Bool if pulsar detection.
    obs_info['pulsar_found'] = 0  # Bool if pulsar detection.
    obs_info['pulsar_dm'] = 0.0  # Pulsar expected DM.
    obs_info['pulsar_snr'] = 0.0  # SNR
    obs_info['pulsar_stats'] = np.zeros(6)
    obs_info['RFI_level'] = 0.0
    obs_info['Mean_SEFD'] = 0.0
    obs_info['psrflux_Sens'] = 0.0
    obs_info['SEFDs_val'] = [0.0]
    obs_info['SEFDs_freq'] = [0.0]
    obs_info['SEFDs_freq_up'] = [0.0]

    #Setting log level
    if opts.loglevel == 'info':
        level_log = logging.INFO
    elif opts.loglevel == 'debug':
        level_log = logging.DEBUG
    else:
        raise ValueError('Need valid loglevel value (info,debug).')

    if level_log == logging.INFO:
        stream = sys.stdout
        format = '%(name)-15s %(levelname)-8s %(message)s'
    else:
        stream = sys.stderr
        format = '%%(relativeCreated)5d (name)-15s %(levelname)-8s %(message)s'

    #Doing search
    try:
        t0 = time.time()

        logging.basicConfig(format=format, stream=stream, level=level_log)

        find_seti_event = FinDoppler(filename,
                                     max_drift=opts.max_drift,
                                     snr=opts.snr,
                                     out_dir=opts.out_dir,
                                     coarse_chans=opts.coarse_chans,
                                     obs_info=obs_info)
        find_seti_event.search()
        ##EE-benshmark    cProfile.runctx('find_seti_event.search()',globals(),locals(),filename='profile_search_M%2.1f_S%2.1f_t%i'%(opts.max_drift,opts.snr,int(os.times()[-1])))

        t1 = time.time()
        print('Search time: %5.2f min' % ((t1 - t0) / 60.))

    except Exception as e:
        logging.exception(e)
        raise Exception(1, '[turbo_SETI] Some issue with FinDoppler.', e)