Python pprint.pprint() Examples

The following are 30 code examples of pprint.pprint(). 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 also want to check out all available functions/classes of the module pprint , or try the search function .
Example #1
Source File: policy.py    From ConvLab with MIT License 7 votes vote down vote up
def mark_not_mentioned(state):
    for domain in state:
        # if domain == 'history':
        if domain not in ['police', 'hospital', 'taxi', 'train', 'attraction', 'restaurant', 'hotel']:
            continue
        try:
            # if len([s for s in state[domain]['semi'] if s != 'book' and state[domain]['semi'][s] != '']) > 0:
                # for s in state[domain]['semi']:
                #     if s != 'book' and state[domain]['semi'][s] == '':
                #         state[domain]['semi'][s] = 'not mentioned'
            for s in state[domain]['semi']:
                if state[domain]['semi'][s] == '':
                    state[domain]['semi'][s] = 'not mentioned'
        except Exception as e:
            # print(str(e))
            # pprint(state[domain])
            pass 
Example #2
Source File: PseudoChannel.py    From pseudo-channel with GNU General Public License v3.0 6 votes vote down vote up
def import_daily_schedule(self):

        """Dropping previous Daily Schedule table before adding the imported data"""
        self.db.remove_all_daily_scheduled_items()
        with open('pseudo-daily_schedule.json') as data_file:    
            data = json.load(data_file)
        #pprint(data)
        for row in data:
            """print row"""
            self.db.import_daily_schedule_table_by_row(
                row[2], 
                row[3], 
                row[4], 
                row[5], 
                row[6], 
                row[7], 
                row[8], 
                row[9], 
                row[10], 
                row[11], 
                row[12],
                row[13],
            )
        print "+++++ Done. Imported Daily Schedule." 
Example #3
Source File: m_g297.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def pos_pyscf ():
    '''converts ase position lists to a long string which is readable for Pyscf'''
    import re        
    import pprint
    for k in sorted (data.keys()):
            nn=sum(1 for c in data[k]['symbols'] if c.isupper()) #number of atoms
            a=re.findall('[A-Z][^A-Z]*', data[k]['symbols']) #atom index e.g. a=['H','Al','Cl']
            num=[]        
            for i in range(len(data[k]['positions'])):
                pos= (str(data[k]['positions'][i]).strip('[]'))
                pos = a[i]+' '+pos
                if (i!= (len(data[k]['positions'])-1)): pos=pos+';'
                num.append(pos)
            pos_py=" " .join(map(str,num))
            data[k]['position_pyscf']=pos_py
    pprint.pprint(data) 
Example #4
Source File: train.py    From ConvLab with MIT License 6 votes vote down vote up
def train(config):
    c = Classifier.classifier(config)
    pprint.pprint(c.tuples.all_tuples)
    print('All tuples:',len(c.tuples.all_tuples))
    model_path = config.get("train", "output")
    model_dir = os.path.dirname(model_path)
    if not os.path.exists(model_dir):
        os.makedirs(model_dir)
    print('output to {}'.format(model_path))
    dataroot = config.get("train", "dataroot")
    dataset = config.get("train", "dataset")
    dw = sutils.dataset_walker(dataset = dataset, dataroot=dataroot, labels=True)
    c = Classifier.classifier(config)
    c.cacheFeature(dw)
    c.train(dw)
    c.save(model_path)
    with zipfile.ZipFile(os.path.join(model_dir, 'svm_multiwoz.zip'), 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.write(model_path) 
Example #5
Source File: nlu.py    From ConvLab with MIT License 6 votes vote down vote up
def parse(self, utterance, context=[]):
        """
        Predict the dialog act of a natural language utterance and apply error model.
        Args:
            utterance (str): A natural language utterance.
        Returns:
            output (dict): The dialog act of utterance.
        """
        # print("nlu input:")
        # pprint(utterance)

        if len(utterance) == 0:
            return {}

        tokens = self.tokenizer.split_words(utterance)
        instance = self.dataset_reader.text_to_instance(tokens)
        outputs = self.model.forward_on_instance(instance)

        return outputs["dialog_act"] 
Example #6
Source File: anaphora_res.py    From adam_qas with GNU General Public License v3.0 6 votes vote down vote up
def get_named_entities(en_doc):
    prop_noun_entities = {}
    prop_noun_entities_pos = {}
    payload = {}
    i = 0
    for ent in en_doc.ents:
        prop_noun_entities_pos[ent.text] = ent.start
        if i < 10:
            payload["name["+str(i)+"]"] = ent.text
            print(ent.label_, ent.text)
        if i == 9:
            prop_noun_entities = get_gender(payload, prop_noun_entities)
            i = 0
        i += 1
    pprint(payload)
    if i < 10:
        prop_noun_entities = get_gender(payload, prop_noun_entities)
    return prop_noun_entities, prop_noun_entities_pos 
Example #7
Source File: scope.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _get_pretty_string(obj):
    """Return a prettier version of obj

    Parameters
    ----------
    obj : object
        Object to pretty print

    Returns
    -------
    s : str
        Pretty print object repr
    """
    sio = StringIO()
    pprint.pprint(obj, stream=sio)
    return sio.getvalue() 
Example #8
Source File: test_svnwc.py    From py with MIT License 6 votes vote down vote up
def test_status_update(self, path1):
        # not a mark because the global "pytestmark" will end up overwriting a mark here
        pytest.xfail("svn-1.7 has buggy 'status --xml' output")
        r = path1
        try:
            r.update(rev=1)
            s = r.status(updates=1, rec=1)
            # Comparing just the file names, because paths are unpredictable
            # on Windows. (long vs. 8.3 paths)
            import pprint
            pprint.pprint(s.allpath())
            assert r.join('anotherfile').basename in [item.basename for
                                                    item in s.update_available]
            #assert len(s.update_available) == 1
        finally:
            r.update() 
Example #9
Source File: redfish.py    From check_redfish with MIT License 5 votes vote down vote up
def get(self, redfish_path):

        if self.__cached_data.get(redfish_path) is None:

            redfish_response = self._rf_get(redfish_path)

            # session invalid
            if redfish_response.status == 401:
                self.get_credentials()
                if self.username is None or self.password is None:
                    self.exit_on_error(f"Username and Password needed to connect to this BMC")

            if redfish_response.status != 404 and redfish_response.status >= 400 and self.session_was_restored is True:
                # reset connection
                self.init_connection(reset=True)

                # query again
                redfish_response = self._rf_get(redfish_path)

            # test if response is valid json and can be decoded
            try:
                redfish_response_json_data = redfish_response.dict
            except Exception:
                redfish_response_json_data = dict({"Members": list()})

            if self.cli_args.verbose:
                pprint.pprint(redfish_response_json_data, stream=sys.stderr)

            if redfish_response_json_data.get("error"):
                error = redfish_response_json_data.get("error").get("@Message.ExtendedInfo")
                self.exit_on_error(
                    "got error '%s' for API path '%s'" % (error[0].get("MessageId"), error[0].get("MessageArgs")))

            self.__cached_data[redfish_path] = redfish_response_json_data

        return self.__cached_data.get(redfish_path) 
Example #10
Source File: perfrepo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def print_stats(response):  # pragma: no cover
    """Finalizes stats for the current request, and prints them possibly."""
    REQUESTS.append(STATS)
    if not os.environ.get("PAGURE_PERFREPO_VERBOSE"):
        return response

    print("Statistics:")
    pprint.pprint(STATS)

    return response 
Example #11
Source File: cleanup-packer-aws-resources.py    From farley-aws-missing-tools with MIT License 5 votes vote down vote up
def get_zombie_packer_security_groups(regions):
    global debug
    output = {}
    for region in regions:
        regionoutput = []
        if debug is True:
            print("Scanning region " + region + " for security groups")

        # Create our EC2 Handler
        ec2 = boto3.client('ec2', region_name=region)

        response = ec2.describe_security_groups(
            Filters=[
                {
                    'Name': 'group-name',
                    'Values': ['packer *'],
                },
            ]
        )
            
        # NOTE:
        # Checking for stales doesn't seem to work, so we'll just try to delete without checking stale
        # # Get our VPCs
        # vpcs = ec2.describe_vpcs()['Vpcs']
        # # Get all stale sgs in every vpc
        # for vpc in vpcs:
        #     stale = ec2.describe_stale_security_groups(VpcId=vpc['VpcId'])['StaleSecurityGroupSet']
        #     pprint(stale)
            
        
        for pair in response['SecurityGroups']:
            regionoutput.append(pair['GroupName'])
        
        #if len(regionoutput) > 0:
        #    stalegroups = ec2.describe_security_groups
        #    for groupname in regionoutput:
                
        output[region] = regionoutput
    return output 
Example #12
Source File: packagemanager.py    From holodeck with MIT License 5 votes vote down vote up
def install(package_name, url=None):
    """Installs a holodeck package.

    Args:
        package_name (:obj:`str`): The name of the package to install
    """

    if package_name is None and url is None:
        raise HolodeckException("You must specify the URL or a valid package name")

    _check_for_old_versions()
    holodeck_path = util.get_holodeck_path()

    if url is None:
        # If the URL is none, we need to derive it
        packages = available_packages()
        if package_name not in packages:
            print("Package not found. Available packages are:", file=sys.stderr)
            pprint.pprint(packages, width=10, indent=4, stream=sys.stderr)
            return

        # example: %backend%/packages/0.1.0/DefaultWorlds/Linux.zip
        url = "{backend_url}packages/{holodeck_version}/{package_name}/{platform}.zip".format(
                    backend_url=BACKEND_URL,
                    holodeck_version=util.get_holodeck_version(),
                    package_name=package_name,
                    platform=util.get_os_key())

    install_path = os.path.join(holodeck_path, "worlds", package_name)

    print("Installing {} from {} to {}".format(package_name, url, install_path))

    _download_binary(url, install_path) 
Example #13
Source File: path.py    From don with Apache License 2.0 5 votes vote down vote up
def cleanup_processes(pid_list):
    pprint.pprint(pid_list)
    for pid in pid_list:
        try:
            os.kill(pid, signal.SIGKILL)
            status_update('Successfully killed pid: %d' % pid)
        except OSError:
            status_update('Process with pid: %d no longer exists' % pid)
            continue
    pass 
Example #14
Source File: client.py    From Pyro5 with MIT License 5 votes vote down vote up
def write_result(result):
    pprint.pprint(result, width=40) 
Example #15
Source File: collector.py    From don with Apache License 2.0 5 votes vote down vote up
def ovs_ofctl_show_br_parser(bridge, parse_this):
    bridge_dict = info['bridges']
    if not bridge_dict.has_key(bridge):
        error('Skipping bridge [' + bridge +
              ']! Supported bridges: ' + str(bridge_dict.keys()))
        return
    bridge_entry = bridge_dict.get(bridge)
    pprint.pprint(bridge_entry)

    for line in parse_this:
        m = re.search('(\d+)\((\S+)\):\s+addr:(\S+)', line)
        if m:
            port_id = m.group(1)
            port = m.group(2)
            port_mac = m.group(3)
            if not bridge_entry['ports'].has_key(port):
                bridge_entry['ports'][port] = {}
            port_entry = bridge_entry['ports'][port]
            port_entry['id'] = port_id
            port_entry['mac'] = port_mac
            continue

        m = re.search('(\w+)\((\S+)\):\s+addr:(\S+)', line)
        if m:
            port_id = m.group(1)
            port = m.group(2)
            port_mac = m.group(3)
            if not bridge_entry['ports'].has_key(port):
                bridge_entry['ports'][port] = {}
            port_entry = bridge_entry['ports'][port]
            port_entry['id'] = port_id
            port_entry['mac'] = port_mac

    pass

# These three are all wrappers for each of the three bridges 
Example #16
Source File: pyparsing.py    From jbox with MIT License 5 votes vote down vote up
def pprint(self, *args, **kwargs):
        """Pretty-printer for parsed results as a list, using the C{pprint} module.
           Accepts additional positional or keyword args as defined for the 
           C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})"""
        pprint.pprint(self.asList(), *args, **kwargs)

    # add support for pickle protocol 
Example #17
Source File: anaphora_res.py    From adam_qas with GNU General Public License v3.0 5 votes vote down vote up
def get_noun_chunks(en_doc, prop_noun_entities):
    payload = {}
    i = 0
    for noun in en_doc.noun_chunks:
        if i < 10:
            payload["name[" + str(i) + "]"] = noun.text
            print(noun.label_, noun.text)
        if i == 9:
            prop_noun_entities = get_gender(payload, prop_noun_entities)
            i = 0
        i += 1
    pprint(payload)
    if i < 10:
        prop_noun_entities = get_gender(payload, prop_noun_entities)
    return prop_noun_entities 
Example #18
Source File: analyzer.py    From don with Apache License 2.0 5 votes vote down vote up
def main():
    check_args()
    analyze(settings['info_file'], settings)
    pprint.pprint(test_suite) 
Example #19
Source File: common.py    From don with Apache License 2.0 5 votes vote down vote up
def execute_cmd(cmd, sudo=False, shell=False, env=None):
    if sudo:
        if shell is False:
            mycmd = ['sudo'] + cmd
        else:
            mycmd = 'sudo ' + cmd
    else:
        mycmd = cmd

    pprint.pprint(mycmd)
    return subprocess.check_output(mycmd,
                                   shell=shell,
                                   stderr=subprocess.STDOUT,
                                   env=env,
                                   universal_newlines=True).replace('\t', '    ') 
Example #20
Source File: plot.py    From don with Apache License 2.0 5 votes vote down vote up
def generate_combined_svg(self):
        cmd = ['/usr/bin/dot', '-Tsvg', self.combined_dot_file,
               '-o', self.combined_svg_file]
        debug(pprint.pformat(cmd))
        subprocess.call(cmd)
        debug('Done generating network SVG') 
Example #21
Source File: perfrepo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def print_stats(response):  # pragma: no cover
    """Finalizes stats for the current request, and prints them possibly."""
    REQUESTS.append(STATS)
    if not os.environ.get("PAGURE_PERFREPO_VERBOSE"):
        return response

    print("Statistics:")
    pprint.pprint(STATS)

    return response 
Example #22
Source File: iosfw.py    From iosfw with MIT License 5 votes vote down vote up
def _swap_transport(self, transport):
        """ Attempts new connection using provided transport protocol """
        self.napalm_args["optional_args"]["transport"] = transport
        self.napalm = self.napalm_driver(**self.napalm_args)
        self.log.debug(pprint.pprint(self.napalm_args))
        try:
            self.napalm.open()
        except (SSHException, ConnectionRefusedError):
            self.log.critical(f"Unable to connect via {transport}. Cannot continue.")
            exit(1) 
Example #23
Source File: bus.py    From vj4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def tail():
  channel = await mq.channel('bus')
  await channel.exchange_declare('bus', 'fanout', auto_delete=True)
  queue = await channel.queue_declare(exclusive=True, auto_delete=True)
  queue_name = queue['queue']
  await channel.queue_bind(queue_name, 'bus', '')

  async def on_message(channel, body, envelope, properties):
    pprint.pprint(bson.BSON.decode(body))

  await channel.basic_consume(on_message, queue_name)
  await channel.close_event.wait() 
Example #24
Source File: analyze_noun_counts.py    From facebook-discussion-tk with MIT License 5 votes vote down vote up
def main():
    global output_file
    num_args = len(sys.argv)
    if num_args < 3:
        print("usage: %s <json-file-1> [json-file-2 ...] <output-csv-file>" % sys.argv[0], file=sys.stderr)
        exit(1)

    json_files = sys.argv[1:num_args - 1]
    output_file = sys.argv[num_args - 1]

    merged_json_data = {}
    for json_file in json_files:
        print("> reading JSON file '%s'..." % json_file)
        with open(json_file) as f:
            json_data = json.load(f)
            for label, data in json_data.items():
                if label not in merged_json_data:
                    merged_json_data[label] = data
                else:
                    merged_json_data[label]['data'].extend(data['data'])

    # pprint(merged_json_data)
    analyse(merged_json_data) 
Example #25
Source File: performance.py    From qb with MIT License 5 votes vote down vote up
def generate(min_count,  pred_file, meta_file, output):
    database = QuestionDatabase()
    data = load_data(pred_file, meta_file, database)
    dan_answers = set(database.page_by_count(min_count, True))
    answers = compute_answers(data, dan_answers)
    stats = compute_statistics(answers).cache()
    stats.to_json(safe_path(output), root_array=False)
    pprint.pprint(stats) 
Example #26
Source File: pyparsing.py    From jbox with MIT License 5 votes vote down vote up
def pprint(self, *args, **kwargs):
        """Pretty-printer for parsed results as a list, using the C{pprint} module.
           Accepts additional positional or keyword args as defined for the 
           C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})"""
        pprint.pprint(self.asList(), *args, **kwargs)

    # add support for pickle protocol 
Example #27
Source File: utils.py    From recruit with Apache License 2.0 5 votes vote down vote up
def print_assert_equal(test_string, actual, desired):
    """
    Test if two objects are equal, and print an error message if test fails.

    The test is performed with ``actual == desired``.

    Parameters
    ----------
    test_string : str
        The message supplied to AssertionError.
    actual : object
        The object to test for equality against `desired`.
    desired : object
        The expected result.

    Examples
    --------
    >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
    >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
    Traceback (most recent call last):
    ...
    AssertionError: Test XYZ of func xyz failed
    ACTUAL:
    [0, 1]
    DESIRED:
    [0, 2]

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import pprint

    if not (actual == desired):
        msg = StringIO()
        msg.write(test_string)
        msg.write(' failed\nACTUAL: \n')
        pprint.pprint(actual, msg)
        msg.write('DESIRED: \n')
        pprint.pprint(desired, msg)
        raise AssertionError(msg.getvalue()) 
Example #28
Source File: factory-package-news.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def do_inspect(self, subcmd, opts, filename, package):
        """${cmd_name}: pprint the package changelog information

        ${cmd_usage}
        ${cmd_option_list}
        """
        f = open(filename, 'rb')
        (v, (pkgs, changelogs)) = pickle.load(
            f, encoding='utf-8', errors='backslashreplace')
        pprint(pkgs[package])
        pprint(changelogs[pkgs[package]['sourcerpm']]) 
Example #29
Source File: factory-package-news.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def do_dump(self, subcmd, opts, *dirs):
        """${cmd_name}: pprint the package changelog information

        ${cmd_usage}
        ${cmd_option_list}
        """
        pprint(self.readChangeLogs(dirs)) 
Example #30
Source File: __init__.py    From Facedancer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default_main(device_or_type, *coroutines):
    """ Simple, default main for FaceDancer emulation.

    Parameters:
        device_type -- The USBDevice type to emulate.
    """

    # Instantiate the relevant device, and connect it to our host.
    parser = argparse.ArgumentParser(description=f"Emulation frontend for {device_or_type.name}(s).")
    parser.add_argument('--print-only', action='store_true', help="Prints information about the device without emulating.")
    parser.add_argument('--suggest', action='store_true', help="Prints suggested code additions after device emualtion is complete.")
    parser.add_argument('-v', '--verbose', help="Controls verbosity. 0=silent, 3=default, 5=spammy", default=3)
    args = parser.parse_args()

    if sys.stdout.isatty():
        log_format = LOG_FORMAT_COLOR
    else:
        log_format = LOG_FORMAT_PLAIN

    # Set up our logging output.
    python_loglevel = 50 - (int(args.verbose) * 10)
    logging.basicConfig(level=python_loglevel, format=log_format)

    if inspect.isclass(device_or_type):
        device = device_or_type()
    else:
        device = device_or_type

    if args.print_only:
        pprint.pprint(device)
        sys.exit(0)

    # Run the relevant code, along with any added coroutines.
    device.emulate(*coroutines)

    if args.suggest:
        device.print_suggested_additions()