Python logging.info() Examples

The following are 30 code examples for showing how to use logging.info(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: svviz   Author: svviz   File: demo.py    License: MIT License 10 votes vote down vote up
def downloadDemo(which):
    try:
        downloadDir = tempfile.mkdtemp()
        archivePath = "{}/svviz-data.zip".format(downloadDir)

        # logging.info("Downloading...")
        downloadWithProgress("http://svviz.github.io/svviz/assets/examples/{}.zip".format(which), archivePath)
        
        logging.info("Decompressing...")
        archive = zipfile.ZipFile(archivePath)
        archive.extractall("{}".format(downloadDir))

        if not os.path.exists("svviz-examples"):
            os.makedirs("svviz-examples/")

        shutil.move("{temp}/{which}".format(temp=downloadDir, which=which), "svviz-examples/")
    except Exception as e:
        print("error downloading and decompressing example data: {}".format(e))
        return False

    if not os.path.exists("svviz-examples"):
        print("error finding example data after download and decompression")
        return False
    return True 
Example 2
Project: indras_net   Author: gcallah   File: agent_pop.py    License: GNU General Public License v3.0 6 votes vote down vote up
def append(self, agent, v=None):
        """
        Appends to agent list.
        """
        if v is None:
            var = agent.get_type()
        else:
            var = v
        logging.info("Adding %s of variety %s" % (agent.name, var))

        if var not in self.vars:
            self.add_variety(var)
            self.graph.add_edge(self, var)

        self.vars[var]["agents"].append(agent)

# we link each agent to the variety
# so we can show their relationship
        self.graph.add_edge(var, agent) 
Example 3
Project: indras_net   Author: gcallah   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run_model(env, prog_file, results_file):
    # Logging is automatically set up for the modeler:
    logging.info("Starting program " + prog_file)

    periods = env.props.get(PERIODS)
    if periods is None:
        periods = -1
    else:
        periods = int(periods)
    # And now we set things running!
    try:
        results = env.run(periods=periods)
    except SystemExit:
        pass
    env.record_results(results_file)
    return results 
Example 4
Project: indras_net   Author: gcallah   File: two_pop_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def postact(self):
        """
        After we are done acting, adopt our new stance.
        If the stance changes our direction, we adopt the extreme
        of the new direction.
        Then move to an empty cell.
        """
        new_direct = self.new_stance.direction()
        curr_direct = self.stance.direction()
        logging.info("For %s: stance = %s, new stance = %s"
                     % (self.name, str(self.stance), str(self.new_stance)))
        if not new_direct.equals(curr_direct):
            self.direction_changed(curr_direct, new_direct)
            # if adopting a new stance direction, we go to the extreme
            self.new_stance = new_direct
        else:
            self.new_stance = self.new_stance.normalize()
        self.stance = self.new_stance
        self.move_to_empty(grid_view=self.my_view) 
Example 5
Project: indras_net   Author: gcallah   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def assign_key(request):
    """
        Assign a key to a user.
    """
    if 'session_id' not in request.session:
        with open("session_id.txt", "w+") as f:
            session_id = f.readline()
            if not session_id:
                session_id = 0
            else:
                session_id = int(session_id)
            session_id += 1
            new_id = session_id
            f.write(str(session_id))

        request.session['session_id'] = new_id
        request.session.modified = True
    else:
        logging.info("This user has a session id: ",
                     request.session['session_id']) 
Example 6
Project: indras_net   Author: gcallah   File: edgebox_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def act(self):
        """
        Act is called in an interactive loop by code
        in the base framework
        """
        super().survey_env()
        for trader in self.neighbor_iter(view=self.my_view):
            for g in self.goods:
                amt = 1
                while self.goods[g]["endow"] >= amt:
                    logging.info(self.name + " is offering "
                                 + str(amt) + " units of "
                                 + g + " to " + trader.name)
                    ans = trader.rec_offer(g, amt, self)
                    if ans == ACCEPT or ans == REJECT:
                        break
                    amt += 1 
Example 7
Project: indras_net   Author: gcallah   File: barter_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def fetch_agents_from_file(self, filenm, agent_type):
        """
        Read in a list of bartering agents from a csv file
        """

        max_detect = self.props.get("max_detect",
                                    ebm.GLOBAL_KNOWLEDGE)
        with open(filenm) as f:
            reader = csv.reader(f)
            for row in reader:
                agent = agent_type(row[0], max_detect=max_detect)
                self.add_agent(agent)
                for i in range(1, len(row) - 2, STEP):
                    good = row[i]
                    self.market.add_good(good)
                    agent.endow(good,
                                int(row[i + 1]),
                                eval("lambda qty: "
                                     + row[i + 2]))
        logging.info("Goods = " + str(self.market)) 
Example 8
Project: indras_net   Author: gcallah   File: old_edgebox.py    License: GNU General Public License v3.0 6 votes vote down vote up
def act(self):
        """
        Act is called in an interactive loop by code
        in the base framework
        """
        super().survey_env()
        for trader shin self.neighbor_iter(view=self.my_view):
            for g in self.goods:
                amt = 1
                while self.goods[g]["endow"] >= amt:
                    logging.info(self.name + " is offering "
                                 + str(amt) + " units of "
                                 + g + " to " + trader.name)
                    ans = trader.rec_offer(g, amt, self)
                    if ans == ACCEPT or ans == REJECT:
                        break
                    amt += 1 
Example 9
Project: svviz   Author: svviz   File: web.py    License: MIT License 6 votes vote down vote up
def run(port=None):
    import webbrowser, threading

    if port is None:
        port = getRandomPort()

    # load()
    url = "http://127.0.0.1:{}/".format(port)
    logging.info("Starting browser at {}".format(url))
    # webbrowser.open_new(url)

    threading.Timer(1.25, lambda: webbrowser.open(url) ).start()

    app.run(
        port=port#,
        # debug=True
    ) 
Example 10
Project: svviz   Author: svviz   File: pairfinder.py    License: MIT License 6 votes vote down vote up
def getToMatchWithSampling(self):
        readIDs = set()

        logging.info("  exceeded number of reads required to begin sampling; performing sampling")
        for region in self.regions:
            for read in self.loadRegion(region.chr(), region.start(), region.end()):
                readIDs.add(read.qname)

        readIDs = random.sample(readIDs, self.sampleReads)

        tomatch = set()
        readsByID = collections.defaultdict(ReadSet)

        for region in self.regions:
            for read in self.loadRegion(region.chr(), region.start(), region.end()):
                if read.qname in readIDs:
                    tomatch.add(read)
                    readsByID[read.qname].add(read)

        return tomatch, readsByID 
Example 11
Project: svviz   Author: svviz   File: insertsizes.py    License: MIT License 6 votes vote down vote up
def chooseOrientation(orientations):
    logging.info("  counts +/-:{:<6} -/+:{:<6} +/+:{:<6} -/-:{:<6} unpaired:{:<6}".format(orientations[False, True], 
                                                    orientations[True, False], 
                                                    orientations[True, True],
                                                    orientations[False, False],
                                                    orientations["unpaired"]))
    ranked = sorted(orientations, key=lambda x: orientations[x])
    chosenOrientations = [ranked.pop()]
    while len(ranked) > 0:
        candidate = ranked.pop()
        if orientations[chosenOrientations[-1]] < 2* orientations[candidate]:
            chosenOrientations.append(candidate)
        else:
            break
    if chosenOrientations[0] == "unpaired":
        chosenOrientations = "any"
    else:
        d = {False: "+", True:"-"}
        chosenOrientations = ["".join(d[x] for x in o) for o in chosenOrientations]
    return chosenOrientations 
Example 12
Project: aospy   Author: spencerahill   File: automate.py    License: Apache License 2.0 6 votes vote down vote up
def _prune_invalid_time_reductions(spec):
    """Prune time reductions of spec with no time dimension."""
    valid_reductions = []
    if not spec['var'].def_time and spec['dtype_out_time'] is not None:
        for reduction in spec['dtype_out_time']:
            if reduction not in _TIME_DEFINED_REDUCTIONS:
                valid_reductions.append(reduction)
            else:
                msg = ("Var {0} has no time dimension "
                       "for the given time reduction "
                       "{1} so this calculation will "
                       "be skipped".format(spec['var'].name, reduction))
                logging.info(msg)
    else:
        valid_reductions = spec['dtype_out_time']
    return valid_reductions 
Example 13
Project: aospy   Author: spencerahill   File: calc.py    License: Apache License 2.0 6 votes vote down vote up
def load(self, dtype_out_time, dtype_out_vert=False, region=False,
             plot_units=False, mask_unphysical=False):
        """Load the data from the object if possible or from disk."""
        msg = ("Loading data from disk for object={0}, dtype_out_time={1}, "
               "dtype_out_vert={2}, and region="
               "{3}".format(self, dtype_out_time, dtype_out_vert, region))
        logging.info(msg + ' ({})'.format(ctime()))
        # Grab from the object if its there.
        try:
            data = self.data_out[dtype_out_time]
        except (AttributeError, KeyError):
            # Otherwise get from disk.  Try scratch first, then archive.
            try:
                data = self._load_from_disk(dtype_out_time, dtype_out_vert,
                                            region=region)
            except IOError:
                data = self._load_from_tar(dtype_out_time, dtype_out_vert)
        # Copy the array to self.data_out for ease of future access.
        self._update_data_out(data, dtype_out_time)
        # Apply desired plotting/cleanup methods.
        if mask_unphysical:
            data = self.var.mask_unphysical(data)
        if plot_units:
            data = self.var.to_plot_units(data, dtype_vert=dtype_out_vert)
        return data 
Example 14
def main(args):
  print_in_box('Validating submission ' + args.submission_filename)
  random.seed()
  temp_dir = args.temp_dir
  delete_temp_dir = False
  if not temp_dir:
    temp_dir = tempfile.mkdtemp()
    logging.info('Created temporary directory: %s', temp_dir)
    delete_temp_dir = True
  validator = validate_submission_lib.SubmissionValidator(temp_dir,
                                                          args.use_gpu)
  if validator.validate_submission(args.submission_filename,
                                   args.submission_type):
    print_in_box('Submission is VALID!')
  else:
    print_in_box('Submission is INVALID, see log messages for details')
  if delete_temp_dir:
    logging.info('Deleting temporary directory: %s', temp_dir)
    subprocess.call(['rm', '-rf', temp_dir]) 
Example 15
def _verify_docker_image_size(self, image_name):
    """Verifies size of Docker image.

    Args:
      image_name: name of the Docker image.

    Returns:
      True if image size is withing the limits, False otherwise.
    """
    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size) if PY3 else long(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE 
Example 16
def copy_submission_to_destination(self, src_filename, dst_subdir,
                                     submission_id):
    """Copies submission to target directory.

    Args:
      src_filename: source filename of the submission
      dst_subdir: subdirectory of the target directory where submission should
        be copied to
      submission_id: ID of the submission, will be used as a new
        submission filename (before extension)
    """

    extension = [e for e in ALLOWED_EXTENSIONS if src_filename.endswith(e)]
    if len(extension) != 1:
      logging.error('Invalid submission extension: %s', src_filename)
      return
    dst_filename = os.path.join(self.target_dir, dst_subdir,
                                submission_id + extension[0])
    cmd = ['gsutil', 'cp', src_filename, dst_filename]
    if subprocess.call(cmd) != 0:
      logging.error('Can\'t copy submission to destination')
    else:
      logging.info('Submission copied to: %s', dst_filename) 
Example 17
Project: neural-fingerprinting   Author: StephanZheng   File: worker.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_without_time_limit(self, cmd):
    """Runs docker command without time limit.

    Args:
      cmd: list with the command line arguments which are passed to docker
        binary

    Returns:
      how long it took to run submission in seconds

    Raises:
      WorkerError: if error occurred during execution of the submission
    """
    cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd
    logging.info('Docker command: %s', ' '.join(cmd))
    start_time = time.time()
    retval = subprocess.call(cmd)
    elapsed_time_sec = long(time.time() - start_time)
    logging.info('Elapsed time of attack: %d', elapsed_time_sec)
    logging.info('Docker retval: %d', retval)
    if retval != 0:
      logging.warning('Docker returned non-zero retval: %d', retval)
      raise WorkerError('Docker returned non-zero retval ' + str(retval))
    return elapsed_time_sec 
Example 18
Project: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def restore_session(self, session_id=None):
        """
        Restore a previous session from a json file
        """
        logging.info("-------------------------Start Restoration of states-------------------------------")

        try:
            base_dir = self.props["base_dir"]
        except:
            base_dir = ""

        if session_id is None:
            session_id = str(self.user.ask("Enter session id: "))
        session_id = str(session_id)
        path = os.path.join(base_dir, "json/" + self.model_nm + session_id + ".json")
        with open(path, "r") as f:
            json_input = f.readline()
        json_input = json.loads(json_input)
        self.from_json(json_input)

        self.restore_agents(json_input)
        self.restore_womb(json_input)
        self.agents.restore_hist_from(json_input["pop_hist"])

        #self.print_env()
        #self.user.tell("Session restored") 
Example 19
Project: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def restore_womb_agent(self, agent_json):
        logging.info("restore_womb_agent not implemented") 
Example 20
Project: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def restore_agent(self, agent_json):
        logging.info("restore_agent not implemented") 
Example 21
Project: indras_net   Author: gcallah   File: prop_args2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_prop_from_env():
    global user_type
    try:
        user_type = os.environ[UTYPE]
    except KeyError:
# this can't be done before logging is set up!
#        logging.info("Environment variable user type not found")
        user_type = TERMINAL
    return user_type 
Example 22
Project: indras_net   Author: gcallah   File: prop_args2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, props, model_name, logfile=None,
                 loglevel=logging.INFO):
        if logfile is None:
            logfile = model_name + ".log"
        fmt = props["log_format"] if "log_format" in props else Logger.DEF_FORMAT
        lvl = props["log_level"] if "log_level" in props else Logger.DEF_LEVEL
        fmd = props["log_fmode"] if "log_fmode" in props else Logger.DEF_FILEMODE
        props["log_fname"] = logfile
# we put the following back in once the model names are fixed
#  fnm = props.get("log_fname", logfile)
        logging.basicConfig(format=fmt,
                            level=lvl,
                            filemode=fmd,
                            filename=logfile)
        logging.info("Logging initialized.") 
Example 23
Project: indras_net   Author: gcallah   File: grid_env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def print_env(self):
        msg = ""
        for row in self.grid:
            for cell in row:
                msg += (str(cell.contents) + ", ")
            msg += "\n"
        logging.info(msg) 
Example 24
Project: indras_net   Author: gcallah   File: grid_env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_agent_color(self):
        logging.info("set_agent_color is not implemented") 
Example 25
Project: indras_net   Author: gcallah   File: prop_args.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_prop_from_env(prop_nm):
    global user_type
    try:
        user_type = os.environ['user_type']
    except KeyError:
# this can't be done before logging is set up!
#        logging.info("Environment variable user type not found")
        user_type = TERMINAL
    return user_type 
Example 26
Project: indras_net   Author: gcallah   File: prop_args.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, props, model_name, logfile=None,
                 loglevel=logging.INFO):
        if logfile is None:
            logfile = model_name + ".log"
        fmt = props.get("log_format", Logger.DEF_FORMAT)
        lvl = props.get("log_level", Logger.DEF_LEVEL)
        fmd = props.get("log_fmode", Logger.DEF_FILEMODE)
        props["log_fname"] = logfile
# we put the following back in once the model names are fixed
#  fnm = props.get("log_fname", logfile)
        logging.basicConfig(format=fmt,
                            level=lvl,
                            filemode=fmd,
                            filename=logfile)
        logging.info("Logging initialized.") 
Example 27
Project: indras_net   Author: gcallah   File: wolfram.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, width, height, model_nm=None, props=None, 
                 rule_id=30):
        super().__init__(name, width, height, torus=False,
                         model_nm=model_nm, postact=True, props=props)
        
        try:
            base_dir = props["base_dir"]
        except:
            base_dir = ""
        
        path = os.path.join(base_dir, "wolfram/wolfram_rules.txt")
        
        try:
            self.rules = self.read_wolfram_rules(path)[rule_id]
        except:
            self.rules = RULE30
            logging.info("Rule dictionary not found. Using the default rule.")

        center_x = floor(self.width // 2)
        top_y = self.height-1
        print("center top = %i, %i" % (center_x, top_y))

        for cell in self:
            (x, y) = cell.coords
            agent = WolframAgent("Cell" + str((x, y)), "Show color", cell)
            self.add_agent(agent, position=False)
            if x == center_x and y == top_y:
                agent.state = B
                agent.postact()
                agent.is_active = False 
Example 28
Project: indras_net   Author: gcallah   File: grid_run.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(prop_dict=None):
    pa = props.PropArgs.create_props(MODEL_NM, prop_dict)

    import indra.utils as utils
    import indra.grid_env as ge
    import models.grid as gm
    (prog_file, log_file, prop_file, results_file) = utils.gen_file_names(MODEL_NM)

    if pa["user_type"] == props.WEB:
        pa["base_dir"] = os.environ["base_dir"]

    # Now we create a minimal environment for our agents to act within:
    env = ge.GridEnv("Test grid env",
                     pa["grid_width"],
                     pa["grid_height"],
                     torus=False,
                     model_nm=MODEL_NM,
                     preact=True,
                     postact=True,
                     props=pa)

    # Now we loop creating multiple agents with numbered names
    # based on the loop variable:
    for i in range(pa["num_agents"]):
        env.add_agent(gm.TestGridAgent(name="agent" + str(i),
                      goal="taking up a grid space!"))

    # let's test our iterator
    for cell in env:
        (x, y) = cell.coords
        logging.info("Contents of cell x = " + str(x)
              + " and y = " + str(y)
              + " is " + str(cell.contents))

    return utils.run_model(env, prog_file, results_file) 
Example 29
Project: indras_net   Author: gcallah   File: grid.py    License: GNU General Public License v3.0 5 votes vote down vote up
def postact(self):
        logging.info("Agent %s postacting" % (self.name)) 
Example 30
Project: indras_net   Author: gcallah   File: gridang_run.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(prop_dict=None):
    pa = props.PropArgs.create_props(MODEL_NM, prop_dict)

    import indra.utils as utils
    import indra.grid_env as ge
    import models.grid as gm
    (prog_file, log_file, prop_file, results_file) = utils.gen_file_names(MODEL_NM)

    if pa["user_type"] == props.WEB:
        pa["base_dir"] = os.environ["base_dir"]
    
    # Now we create a minimal environment for our agents to act within:
    env = ge.GridEnv("Test grid env",
                     pa["grid_width"],
                     pa["grid_height"],
                     torus=False,
                     model_nm=MODEL_NM,
                     preact=True,
                     postact=True,
                     props=pa)
    
    # Now we loop creating multiple agents with numbered names
    # based on the loop variable:
    for i in range(pa["num_agents"]):
        env.add_agent(gm.TestGridAgent(name="agent" + str(i),
                      goal="taking up a grid space!"))
    
    # let's test our iterator
    for cell in env:
        (x, y) = cell.coords
        logging.info("Contents of cell x = " + str(x)
              + " and y = " + str(y)
              + " is " + str(cell.contents))
        
    return utils.run_model(env, prog_file, results_file)