Python six.print_() Examples
The following are 30
code examples of six.print_().
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
six
, or try the search function
.
Example #1
Source File: fitting.py From python-casacore with GNU General Public License v2.0 | 6 votes |
def addconstraint(self, x, y=0, fnct=None, fid=0): """Add constraint.""" self._checkid(fid) i = 0 if "constraint" in self._fitids[fid]: i = len(self._fitids[fid]["constraint"]) else: self._fitids[fid]["constraint"] = {} # dict key needs to be string i = str(i) self._fitids[fid]["constraint"][i] = {} if isinstance(fnct, functional): self._fitids[fid]["constraint"][i]["fnct"] = fnct.todict() else: self._fitids[fid]["constraint"][i]["fnct"] = \ functional("hyper", len(x)).todict() self._fitids[fid]["constraint"][i]["x"] = [float(v) for v in x] self._fitids[fid]["constraint"][i]["y"] = float(y) six.print_(self._fitids[fid]["constraint"])
Example #2
Source File: device.py From mobile-ai-bench with Apache License 2.0 | 6 votes |
def __init__(self, device_dict): """ init device with device dict """ diff = set(device_dict.keys()) - set(YAMLKeyword.__dict__.keys()) if len(diff) > 0: six.print_('Wrong key detected:') six.print_(diff) raise KeyError(str(diff)) self.__dict__.update(device_dict) if self.system == SystemType.android: pass elif self.system == SystemType.arm_linux: try: sh.ssh('-q', '%s@%s' % (self.username, self.address), 'exit') except sh.ErrorReturnCode as e: six.print_('device connect failed, ' 'please check your authentication', file=sys.stderr) raise e ##################### # public interface # #####################
Example #3
Source File: api.py From Mastering-Python-for-Networking-and-Security with MIT License | 6 votes |
def run_console(config): """ :param config: GlobalParameters option instance :type config: `GlobalParameters` :raises: TypeError """ if not isinstance(config, GlobalParameters): raise TypeError("Expected GlobalParameters, got '%s' instead" % type(config)) six.print_(colored("[*]", "blue"), "Starting port_scanning execution") run(config) six.print_(colored("[*]", "blue"), "Done!") # ---------------------------------------------------------------------- # # API call # # ----------------------------------------------------------------------
Example #4
Source File: elitech_device.py From elitech-datareader with MIT License | 6 votes |
def command_raw_send(args): device = elitech.Device(args.serial_port, args.ser_baudrate, args.ser_timeout) request_bytes = _bin(args.req) res = device.raw_send(request_bytes, args.res_len) print("\nresponse length={}".format(len(res))) for i, b in enumerate(res): if six.PY2: six.print_("{:02X} ".format(ord(b)), sep='', end='') else: six.print_("{:02X} ".format(b), end='') if (i + 1) % 16 == 0: six.print_() six.print_()
Example #5
Source File: tcping.py From tcping with MIT License | 6 votes |
def statistics(self, n): conn_times = self._conn_times if self._conn_times != [] else [0] minimum = '{0:.2f}ms'.format(min(conn_times)) maximum = '{0:.2f}ms'.format(max(conn_times)) average = '{0:.2f}ms'.format(avg(conn_times)) success_rate = self._success_rate() + '%' self.print_.add_statistics(Statistics( self._host, self._port, self._successed, self._failed, success_rate, minimum, maximum, average))
Example #6
Source File: device.py From mobile-ai-bench with Apache License 2.0 | 6 votes |
def pull(self, src_path, dst_path='.'): if self.system == SystemType.android: sh_commands.adb_pull(src_path, dst_path, self.address) elif self.system == SystemType.arm_linux: if os.path.isdir(dst_path): exist_file = dst_path + '/' + src_path.split('/')[-1] if os.path.exists(exist_file): sh.rm('-rf', exist_file) elif os.path.exists(dst_path): sh.rm('-f', dst_path) try: sh.scp('-r', '%s@%s:%s' % (self.username, self.address, src_path), dst_path) except sh.ErrorReturnCode_1 as e: six.print_('Error msg {}'.format(e), file=sys.stderr) return
Example #7
Source File: decision_task_poller.py From botoflow with Apache License 2.0 | 6 votes |
def single_poll(self, next_page_token=None): poll_time = time.time() try: kwargs = {'domain': self.domain, 'taskList': {'name': self.task_list}, 'identity': self.identity} if next_page_token is not None: kwargs['nextPageToken'] = next_page_token # old botocore throws TypeError when unable to establish SWF connection return self.worker.client.poll_for_decision_task(**kwargs) except KeyboardInterrupt: # sleep before actually exiting as the connection is not yet closed # on the other end sleep_time = 60 - (time.time() - poll_time) six.print_("Exiting in {0}...".format(sleep_time), file=sys.stderr) time.sleep(sleep_time) raise
Example #8
Source File: tagfix.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def globals(): '''Re-build the cache for all of the globals in the database.''' # read all function and data tags addr, tags = fetch_globals() # update the global state six.print_(u'globals: updating global name refs', file=output) for k, v in six.iteritems(tags): internal.comment.globals.set_name(k, v) six.print_(u'globals: updating global address refs', file=output) for k, v in six.iteritems(addr): internal.comment.globals.set_address(k, v) return addr, tags
Example #9
Source File: tagfix.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fetch_globals(): """Fetch the reference count of all of the global tags for both functions and non-functions. Returns the tuple `(address, tags)` where the `address` and `tags` fields are both dictionaries containing the reference count for the addresses and tag names. """ # read addr and tags from all functions/globals faddr, ftags = fetch_globals_functions() daddr, dtags = fetch_globals_data() # consolidate tags into individual dictionaries six.print_(u'globals: aggregating results', file=output) addr, tags = dict(faddr), dict(ftags) for k, v in six.iteritems(daddr): addr[k] = addr.get(k, 0) + v for k, v in six.iteritems(dtags): tags[k] = tags.get(k, 0) + v six.print_(u"globals: found {:d} addresses".format(len(addr)), file=output) six.print_(u"globals: found {:d} tags".format(len(tags)), file=output) return addr, tags
Example #10
Source File: tagfix.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fetch_globals_functions(): """Fetch the reference count for the global tags (function) in the database. Returns the tuple `(address, tags)` where the `address` and `tags` fields are both dictionaries containing the reference count for the addresses and tag names. """ addr, tags = {}, {} t = len(list(db.functions())) for i, ea in enumerate(db.functions()): ui.navigation.auto(ea) six.print_(u"globals: fetching tag from function {:#x} : {:d} of {:d}".format(ea, i, t), file=output) res = func.tag(ea) #res.pop('name', None) for k, v in six.iteritems(res): addr[ea] = addr.get(ea, 0) + 1 tags[k] = tags.get(k, 0) + 1 continue return addr, tags
Example #11
Source File: load_into_pg.py From stackexchange-dump-to-postgres with MIT License | 6 votes |
def show_progress(block_num, block_size, total_size): """Display the total size of the file to download and the progress in percent""" global file_part if file_part is None: suffixes = ['B', 'KB', 'MB', 'GB', 'TB'] suffixIndex = 0 pp_size = total_size while pp_size > 1024: suffixIndex += 1 # Increment the index of the suffix pp_size = pp_size / 1024.0 # Apply the division six.print_('Total file size is: {0:.1f} {1}' .format(pp_size, suffixes[suffixIndex])) six.print_("0 % of the file downloaded ...\r", end="", flush=True) file_part = 0 downloaded = block_num * block_size if downloaded < total_size: percent = 100 * downloaded / total_size if percent - file_part > 1: file_part = percent six.print_("{0} % of the file downloaded ...\r".format(int(percent)), end="", flush=True) else: file_part = None six.print_("")
Example #12
Source File: load_into_pg.py From stackexchange-dump-to-postgres with MIT License | 6 votes |
def moveTableToSchema(table, schemaName, dbConnectionParam): try: with pg.connect(dbConnectionParam) as conn: with conn.cursor() as cur: # create the schema cur.execute('CREATE SCHEMA IF NOT EXISTS ' + schemaName + ';') conn.commit() # move the table to the right schema cur.execute('ALTER TABLE ' + table + ' SET SCHEMA ' + schemaName + ';') conn.commit() except pg.Error as e: six.print_("Error in dealing with the database.", file=sys.stderr) six.print_("pg.Error ({0}): {1}".format(e.pgcode, e.pgerror), file=sys.stderr) six.print_(str(e), file=sys.stderr) except pg.Warning as w: six.print_("Warning from the database.", file=sys.stderr) six.print_("pg.Warning: {0}".format(str(w)), file=sys.stderr) #############################################################
Example #13
Source File: enumeration.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def list(**type): '''List all of the enumerations within the database that match the keyword specified by `type`.''' res = builtins.list(iterate(**type)) maxindex = max(builtins.map(idaapi.get_enum_idx, res) or [1]) maxname = max(builtins.map(utils.fcompose(idaapi.get_enum_name, len), res) or [0]) maxsize = max(builtins.map(size, res) or [0]) cindex = math.ceil(math.log(maxindex or 1)/math.log(10)) try: cmask = max(builtins.map(utils.fcompose(mask, utils.fcondition(utils.fpartial(operator.eq, 0))(utils.fconstant(1), utils.fidentity), math.log, functools.partial(operator.mul, 1.0/math.log(8)), math.ceil), res) or [database.config.bits()/4.0]) except: cmask = 0 for n in res: name = idaapi.get_enum_name(n) six.print_(u"[{:{:d}d}] {:>{:d}s} & {:<{:d}x} ({:d} members){:s}".format(idaapi.get_enum_idx(n), int(cindex), utils.string.of(name), maxname, mask(n), int(cmask), len(builtins.list(members(n))), u" // {:s}".format(comment(n)) if comment(n) else '')) return ## members
Example #14
Source File: progress.py From mead-baseline with Apache License 2.0 | 6 votes |
def update(self, step=1): """Update progress bar by number of `steps` :param step: The number of tasks completed :return: """ self.current += step percent = self.current / float(self.total) size = int(self.width * percent) remaining = self.total - self.current bar = "[" + self.symbol * size + " " * (self.width - size) + "]" args = { "total": self.total, "bar": bar, "current": self.current, "percent": percent * 100, "remaining": remaining, } self.print_("\r" + self.fmt % args, end="")
Example #15
Source File: tableutil.py From python-casacore with GNU General Public License v2.0 | 6 votes |
def tabledelete(tablename, checksubtables=False, ack=True): """Delete a table on disk. It is the same as :func:`table.delete`, but without the need to open the table first. """ tabname = _remove_prefix(tablename) t = table(tabname, ack=False) if t.ismultiused(checksubtables): six.print_('Table', tabname, 'cannot be deleted; it is still in use') else: t = 0 table(tabname, readonly=False, _delete=True, ack=False) if ack: six.print_('Table', tabname, 'has been deleted')
Example #16
Source File: __init__.py From elitech-datareader with MIT License | 6 votes |
def _talk(self, request, response): """ :type request: RequestMessage """ ba = request.to_bytes() if (self.debug): print("\nba length={}".format(len(ba))) for i, b in enumerate(ba): if six.PY2: six.print_("{:02X} ".format(ord(b)), sep='', end='') else: six.print_("{:02X} ".format(b), end='') if (i + 1) % 16 == 0: six.print_() six.print_() self._ser.write(ba) response.read(self._ser) return response
Example #17
Source File: cfn_custom_resource.py From cfn-custom-resource with Mozilla Public License 2.0 | 6 votes |
def send_response(cls, resource, url, response_content): if url == cls.DUMMY_RESPONSE_URL_SILENT: return elif url == cls.DUMMY_RESPONSE_URL_PRINT: six.print_(json.dumps(response_content, indent=2)) else: put_response = requests.put(url, data=json.dumps(response_content)) status_code = put_response.status_code response_text = put_response.text body_text = "" if status_code // 100 != 2: body_text = "\n" + response_text resource._base_logger.debug("Status code: {} {}{}".format(put_response.status_code, http_client.responses[put_response.status_code], body_text)) return put_response
Example #18
Source File: main.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def output_profile_result(env): stdout_trap = six.StringIO() env.profile_deco.print_stats(stdout_trap) profile_output = stdout_trap.getvalue() profile_output = profile_output.rstrip() six.print_(profile_output) env.event_bus.publish_event(Event(EVENT.ON_LINE_PROFILER_RESULT, result=profile_output))
Example #19
Source File: strategy_loader_help.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def compile_strategy(source_code, strategy, scope): try: code = compile(source_code, strategy, 'exec') six.exec_(code, scope) return scope except Exception as e: exc_type, exc_val, exc_tb = sys.exc_info() exc_val = patch_user_exc(exc_val, force=True) try: msg = str(exc_val) except Exception as e1: msg = "" six.print_(e1) error = CustomError() error.set_msg(msg) error.set_exc(exc_type, exc_val, exc_tb) stackinfos = list(traceback.extract_tb(exc_tb)) if isinstance(e, (SyntaxError, IndentationError)): error.add_stack_info(exc_val.filename, exc_val.lineno, "", exc_val.text) else: for item in stackinfos: filename, lineno, func_name, code = item if strategy == filename: error.add_stack_info(*item) # avoid empty stack if error.stacks_length == 0: error.add_stack_info(*item) raise CustomException(error)
Example #20
Source File: coordinates.py From python-casacore with GNU General Public License v2.0 | 5 votes |
def summary(self): six.print_(str(self))
Example #21
Source File: test_six.py From c4ddev with MIT License | 5 votes |
def test_print_exceptions(): py.test.raises(TypeError, six.print_, x=3) py.test.raises(TypeError, six.print_, end=3) py.test.raises(TypeError, six.print_, sep=42)
Example #22
Source File: image.py From python-casacore with GNU General Public License v2.0 | 5 votes |
def view(self, tempname='/tmp/tempimage'): """Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'. """ import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system('casaviewer ' + self.name() + ' &') elif len(tempname) > 0: six.print_(" making a persistent copy in " + tempname) six.print_(" which should be deleted after the viewer has ended") self.saveas(tempname) os.system('casaviewer ' + tempname + ' &') else: six.print_("Cannot view because the image is in memory only.") six.print_("You can browse a persistent copy of the image like:") six.print_(" t.view('/tmp/tempimage')") else: six.print_("casaviewer cannot be found")
Example #23
Source File: wxtablebrowser.py From python-casacore with GNU General Public License v2.0 | 5 votes |
def OnRightDown(self, event): # added six.print_(self.GetSelectedRows()) # added # ---------------------------------------------------------------------------
Example #24
Source File: test_task_queue.py From pyspider with Apache License 2.0 | 5 votes |
def test_task_queue_in_time_order(self): tq = TaskQueue(rate=300, burst=1000) queues = dict() tasks = dict() for i in range(0, 100): it = InQueueTask(str(i), priority=int(i // 10), exetime=0) tq.put(it.taskid, it.priority, it.exetime) if it.priority not in queues: queues[it.priority] = Queue.Queue() q = queues[it.priority] # type:Queue.Queue q.put(it) tasks[it.taskid] = it # six.print_('put, taskid=', it.taskid, 'priority=', it.priority, 'exetime=', it.exetime) for i in range(0, 100): task_id = tq.get() task = tasks[task_id] q = queues[task.priority] # type: Queue.Queue expect_task = q.get() self.assertEqual(task_id, expect_task.taskid) self.assertEqual(task.priority, int(9 - i // 10)) # six.print_('get, taskid=', task.taskid, 'priority=', task.priority, 'exetime=', task.exetime) self.assertEqual(tq.size(), 100) self.assertEqual(tq.priority_queue.qsize(), 0) self.assertEqual(tq.processing.qsize(), 100) for q in six.itervalues(queues): # type:Queue.Queue self.assertEqual(q.qsize(), 0) pass
Example #25
Source File: test_six.py From c4ddev with MIT License | 5 votes |
def test_print_encoding(monkeypatch): # Fool the type checking in print_. monkeypatch.setattr(six, "file", six.BytesIO, raising=False) out = six.BytesIO() out.encoding = "utf-8" out.errors = None six.print_(six.u("\u053c"), end="", file=out) assert out.getvalue() == six.b("\xd4\xbc") out = six.BytesIO() out.encoding = "ascii" out.errors = "strict" py.test.raises(UnicodeEncodeError, six.print_, six.u("\u053c"), file=out) out.errors = "backslashreplace" six.print_(six.u("\u053c"), end="", file=out) assert out.getvalue() == six.b("\\u053c")
Example #26
Source File: enumeration.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def list(cls, enum): '''List all the members belonging to the enumeration identified by `enum`.''' # FIXME: make this consistent with every other .list using the matcher class eid = by(enum) res = builtins.list(cls.iterate(eid)) maxindex = max(builtins.map(utils.first, enumerate(res)) or [1]) maxvalue = max(builtins.map(utils.fcompose(member.value, "{:#x}".format, len), res) or [1]) for i, mid in enumerate(res): six.print_(u"[{:d}] 0x{:>0{:d}x} {:s}".format(i, member.value(mid), maxvalue, member.name(mid))) return
Example #27
Source File: structure.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def list(**type): '''List all the structures within the database that match the keyword specified by `type`.''' res = builtins.list(iterate(**type)) maxindex = max(builtins.map(utils.fcompose(operator.attrgetter('index'), "{:d}".format, len), res) or [1]) maxname = max(builtins.map(utils.fcompose(operator.attrgetter('name'), utils.fdefault(''), len), res) or [1]) maxsize = max(builtins.map(utils.fcompose(operator.attrgetter('size'), "{:+#x}".format, len), res) or [1]) for st in res: six.print_(u"[{:{:d}d}] {:>{:d}s} {:<+#{:d}x} ({:d} members){:s}".format(idaapi.get_struc_idx(st.id), maxindex, st.name, maxname, st.size, maxsize, len(st.members), u" // {!s}".format(st.tag() if '\n' in st.comment else st.comment) if st.comment else '')) return
Example #28
Source File: __main__.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def generate_config(directory): """ Generate default config file """ default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_config_path) # For Mod Cli
Example #29
Source File: structure.py From ida-minsc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def list(self, **type): '''List all the members within the structure that match the keyword specified by `type`.''' res = builtins.list(self.iterate(**type)) maxindex = max(builtins.map(utils.fcompose(operator.attrgetter('index'), "{:d}".format, len), res) or [1]) maxoffset = max(builtins.map(utils.fcompose(operator.attrgetter('offset'), "{:x}".format, len), res) or [1]) maxsize = max(builtins.map(utils.fcompose(operator.attrgetter('size'), "{:+#x}".format, len), res) or [1]) maxname = max(builtins.map(utils.fcompose(operator.attrgetter('name'), utils.string.repr, len), res) or [1]) maxtype = max(builtins.map(utils.fcompose(operator.attrgetter('type'), utils.string.repr, len), res) or [1]) maxtypeinfo = max(builtins.map(utils.fcompose(operator.attrgetter('typeinfo'), "{!s}".format, operator.methodcaller('replace', ' *', '*'), len), res) or [0]) for m in res: six.print_(u"[{:{:d}d}] {:>{:d}x}:{:<+#{:d}x} {:>{:d}s} {:<{:d}s} {:{:d}s} (flag={:x},dt_type={:x}{:s}){:s}".format(m.index, maxindex, m.offset, int(maxoffset), m.size, maxsize, "{!s}".format(m.typeinfo).replace(' *', '*'), int(maxtypeinfo), utils.string.repr(m.name), int(maxname), m.type, int(maxtype), m.flag, m.dt_type, '' if m.typeid is None else ",typeid={:x}".format(m.typeid), u" // {!s}".format(m.tag() if '\n' in m.comment else m.comment) if m.comment else '')) return
Example #30
Source File: tableutil.py From python-casacore with GNU General Public License v2.0 | 5 votes |
def tablestructure(tablename, dataman=True, column=True, subtable=False, sort=False): """Print the structure of a table. It is the same as :func:`table.showstructure`, but without the need to open the table first. """ t = table(tablename, ack=False) six.print_(t.showstructure(dataman, column, subtable, sort))