def print( message, sessionId="current_session", pageId="current_page", destination="client", ): """Sends print statements to the scripting console when in the Designer. When in a Session, sends print statements to the output console. This function makes scripting diagnostics easier. Args: message (str): The print statement that will be displayed on the console. sessionId (str): Identifier of the Session to target. If omitted the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. destination (str): Where the message should be printed. If specified, must be "client", "gateway", or "all". Default is "client". Optional. """ builtins.print(message, sessionId, pageId, destination)
def sendMessage( messageType, payload, scope="page", sessionId="current_session", pageId="current_page", ): """Send a message to a message handler within the same session. Args: messageType (str): The message type that will be invoked. Message handlers configured within the project are listening for messages of a specific messageType. payload (dict): A python dictionary representing any parameters that will be passed to the message handler. scope (str): The scope that the message should be delivered to. Valid values are "session", "page", or "view". If omitted, "page" will be used. Optional. sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(messageType, payload, scope, sessionId, pageId)
def print(*objects, **kwargs): """ Overload the print function to adapt for the encoding bug in Windows console. It will try to convert text to the console encoding before printing to prevent crashes. """ try: stream = kwargs.get('file', None) if stream is None: stream = sys.stdout enc = stream.encoding if enc is None: enc = sys.getdefaultencoding() except AttributeError: return __builtin__.print(*objects, **kwargs) texts = [] for object in objects: try: original_text = str(object).decode(enc, errors='replace') except UnicodeEncodeError: original_text = unicode(object).encode(enc, errors='replace').decode(enc, errors='replace') texts.append(original_text) return __builtin__.print(*texts, **kwargs)
def print(*args, **kwargs): flush = kwargs.pop('flush', False) builtins.print(*args, **kwargs) if flush: file = kwargs.get('file') if file is None: file = sys.stdout file.flush()
def login(sessionId="current_session", pageId="current_page", forceAuth=False): """Triggers a login event that will allow the user to login with the project's configured Identity Provider (IdP). For this function to work, an Identity Provider must be set in Perspective project properties. This is particularly useful when you want it to be possible to start a session without authentication and sign in to access certain restricted features. Args: sessionId (str): Identifier of the Session to target. If omitted the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. forceAuth (bool): Determines if Ignition should ask the Identity Provider to re-authenticate the user, even if the user is already signed into the Identity Provider. If set to True, then the Identity Provider will ask the user to re-enter their credentials. If set to False, then the Gateway will request that the Identity Provider use the last provided credentials for the session, potentially allowing re-authentication without requiring the user to re-type their credentials. Note that support for this argument is determined by the Identity Provider; the IdP may choose to ignore this request. If this parameter is omitted, then the function will use the re-authentication setting defined under Project Properties. Optional. """ builtins.print(sessionId, pageId, forceAuth)
def alterLogging( remoteLoggingEnabled=False, level="info", remoteLoggingLevel="warn", sessionId="current_session", pageId="current_page", ): """Changes Perspective Session logging attributes and levels. All parameters are optional, with the caveat that at least one of them needs to be used. Args: remoteLoggingEnabled (bool): Will enable remote logging if True. Remote logging will send log events from the Session to the Gateway under the perspective.client logger if the meet the remoteLevel logging level requirement. Optional. level (str): The desired Session logging level. Possible values are: all, trace, debug, info, warn, error, fatal, off. The default is info. Optional. remoteLoggingLevel (str): The desired remote logging level. Possible values are: all, trace, debug, info, warn, error, fatal, off. The default is warn. Optional. sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(remoteLoggingEnabled, level, remoteLoggingLevel, sessionId, pageId)
def print(*pargs, **pkwargs): global logging if args.daemonize: __builtin__.print(*pargs) logging.info(*pargs, **pkwargs) else: __builtin__.print(*pargs)
def wrp_setter(*args, **kwargs): if not utool.QUIET and utool.VERBOSE: print('[SET]: ' + func.func_name) import __builtin__ __builtin__.print('\n' + utool.func_str(func, args, kwargs) + '\n') #print('set: func_name=%r, args=%r, kwargs=%r' % (func.func_name, args, kwargs)) return func(*args, **kwargs)
def do_popauth(self, user_password): """ popauth <user> <pass> Try to authenticate on pop3 server with specified user and password """ def get_code(line): try: return line.split(" ")[0] except IndexError: return "" if user_password: try: user, password = tuple(user_password.split(" ")) if user and password: self.telnet.write("USER {0}\n".format(user)) self.telnet.read_timeout() self.telnet.write("PASS {0}\n".format(password)) c = get_code(self.telnet.read_available()) if c != "-ERR": __builtin__.print("[+] Login successful with {0}:{1}".format(user, password)) else: __builtin__.print("[-] Login failed!") else: __builtin__.print("Error: You must specify both user and password") except ValueError: __builtin__.print("Error: You must specify both user and password") else: __builtin__.print("Error: You must specify user and password")
def update(i): xi, yi = next(gen) y.append(yi) x.append(xi) ax.clear() ax.plot(x, y) print(i, ':', xi, ': ', yi)
def print(*args, **kwargs): s = inspect.stack() __builtin__.print( "\033[47m%s@%s(%s):\033[0m " % (rpad(s[1][1], 20), lpad(str(s[1][3]), 10), rpad(str(s[1][2]), 4)), end="") return __builtin__.print(*args, **kwargs)
def signal_handler(*args): console = InterctiveConsole(t) try: console.cmdloop() except KeyboardInterrupt: __builtin__.print("\n[-] Stopping interactive console") t.interact()
def do_popmail(self, line): """ popmails Try to list pop3 mails after a successful login """ self.telnet.write("LIST\n") __builtin__.print(self.telnet.read_available())
def over_print(output): ''' Print and duplicate the print to an event ''' print_event = {'data': output, 'outputter': 'pprint'} func_globals['__jid_event__'].fire_event(print_event, 'print') __builtin__.print(output) # and do the old style printout
def print(*args, **kwargs): # Response delay if true in settings if extractConfig['RESPONSE_DELAY']['value'].lower() == 'true': time.sleep(1) # All caps output if true in settings for arg in args: if isinstance(arg, str) and extractConfig['OUTPUT_IN_CAPS']['value'].lower() == 'true': return __builtin__.print(arg.upper(), **kwargs) return __builtin__.print(*args, **kwargs)
def __call__(self, *args, **kwargs): self.map_cls.get_executor_stack().append(None) try: return self.func(*args, **kwargs) except: print(self.map_cls.__name__ + " error:") _coconut.traceback.print_exc() raise finally: self.map_cls.get_executor_stack().pop()
def do_httpget(self, host): """ httpget <hostname> Send an HTTP GET with specified hostname as Host """ if host: self.telnet.write("GET / HTTP/1.1\r\nHost: {0}\r\n\r\n".format(host)) __builtin__.print(self.telnet.read_available()) else: __builtin__.print("Error: You must specify an hostname")
def print(*args, **kwargs): """My custom print() function.""" # Adding new arguments to the print function signature # is probably a bad idea. # Instead consider testing if custom argument keywords # are present in kwargs time = strftime("%m/%d-%H:%M:%S", gmtime()) if 'builtin' in kwargs: if kwargs['builtin']: return __builtin__.print(*args) return __builtin__.print("{} |- [INFO] {}".format(time, args[0]), **kwargs)
def refresh(sessionId="current_session", pageId="current_page"): """Triggers a refresh of the page. Args: sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(sessionId, pageId)
def do_httppost(self, host): """ httppost <hostname> Send an HTTP POST with specified hostname as Host """ if host: self.telnet.write("POST / HTTP/1.1\r\nHost: {0}\r\nContent-Type: application/x-www-form-urlencoded\r\n" "Content-Length: 4\r\n\r\ntest".format(host)) __builtin__.print(self.telnet.read_available()) else: __builtin__.print("Error: You must specify an hostname")
def read_available(self): """ Read data when available """ text = "" while 1: rfd, wfd, xfd = select.select([self, sys.stdin], [], []) if self in rfd: try: text = self.read_very_eager() break except EOFError: __builtin__.print('*** Connection closed by remote host ***') break return text
def navigateBack(sessionId=None, pageId=None): """Navigate the session to a specified view or mounted page. This is similar to a browser's "back" function. Args: sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. Optional. pageId (str): Identifier of the page to target. If omitted, the current page will be used automatically. Optional. """ builtins.print(sessionId, pageId)
def vibrateDevice(duration, sessionId="current_session"): """When called from the Perspective mobile app, will cause the device to vibrate for the specified number of milliseconds. Args: duration (int): The duration in milliseconds to vibrate the device. sessionId (str): Identifier of the Session to target. If omitted the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. """ builtins.print(duration, sessionId)
def print(*args, **kwargs): args = list(args) try: if not COLORS and u"\033" in args[0]: args[0] = strip_ansi(args[0]) except: pass with print_mutex: t = time.strftime("%H%M%S ") builtins.print( t + str(args[0] if args else u"").replace(u"\n", u"\n" + t), *args[1:], **kwargs)
def print(*args, **kwargs): """custom print() function.""" # A hack. Look inside and if args is empty, do not do anything, # just call the default print function. if args: callers_frame_idx = 1 (frame, filename, lineno, function_name, lines, index) = inspect.getouterframes( inspect.currentframe())[callers_frame_idx] #frameinfo = inspect.getframeinfo(inspect.currentframe()) basename = fops.get_file_name_from_path(filename) f = kwargs.get('file', sys.stdout) __builtin__.print('{}:{}::'.format(basename, lineno), end='', file=f) return __builtin__.print(*args, **kwargs)
def navigateForward(sessionId=None, pageId=None): """Navigate the session to a specified view or mounted page. This is similar to a browser's "forward" function. Args: sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the page to target. If omitted, the current page will be used automatically. Optional. """ builtins.print(sessionId, pageId)
def do_smtpmail(self, recipient): """ smtpmail <recipient> Try to use smtp server as an open relay """ def get_code(line): try: return line.split(" ")[0] except IndexError: return "" self.telnet.write("HELO domain.com\n") self.telnet.read_available() self.telnet.write("MAIL FROM: <root@localhot>\n") c = get_code(self.telnet.read_available()) if c == "250": self.telnet.write("RCPT TO: <{0}>\n".format(recipient)) c = get_code(self.telnet.read_available()) if c == "250": self.telnet.write("DATA\n") self.telnet.read_available() self.telnet.write("test\r\n.\r\n") c = get_code(self.telnet.read_available()) if c == "250": __builtin__.print("[+] Mail sent!") else: __builtin__.print("[-] Error while sending mail!") else: __builtin__.print("[-] Error while setting recipient!") else: __builtin__.print("[-] Error while setting sender!")
def oprint(level, string): """ Helper for printing to stdout Parameters --------- level: integer print level of the string (0: None, 1: results, 3: +progress, 4+: excess) string: string string to be printed """ if settings.print_level >= level: __builtin__.print(string)
def eprint(level, string): """ Helper for printing to stderr Parameters --------- level: integer print level of the string (0: None, 1: errors, 2: +warnings, 4+: excess) string: string string to be printed """ if settings.print_level >= level: __builtin__.print(string, file=sys.stderr)
def logout(sessionId="current_session", pageId="current_page"): """Triggers a logout event, which will log the user out. For this function to work, an Identity Provider must be set in the Perspective project properties. Args: sessionId (str): Identifier of the Session to target. If omitted the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(sessionId, pageId)
def closePopup(id, sessionId="current_session", pageId="current_page"): """Closes a popup View. Args: id (str): The unique identifier for the the popup, given to the popup when first opened. If given an empty string, then the most recently focused popup will be closed. sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(id, sessionId, pageId)
def closeDock(id, sessionId=None, pageId=None): """Closes a docked view. Args: id (str): The unique, preconfigured 'Dock ID' for the docked View. Is specified when a View is assigned as docked for a particular Page (in Page Configuration). sessionId (str): Identifier of the Session to target. If omitted, the current Session will be used automatically. When targeting a different session, then the pageId parameter must be included in the call. Optional. pageId (str): Identifier of the Page to target. If omitted, the current Page will be used automatically. Optional. """ builtins.print(id, sessionId, pageId)
def n_print(*args, **kwargs): """Print with colors""" try: c = color_dict[kwargs.pop("color")] args = (c + str(args[0]),) + args[1:] + (colorama.Style.RESET_ALL,) except KeyError as e: pass except IndexError as e: pass return __builtin__.print(*args, **kwargs)
def print(*args, **kwargs): if "end" not in kwargs: kwargs["end"] = "" r = __builtin__.print(*args, **kwargs) __builtin__.print(" ") else: r = __builtin__.print(*args, **kwargs) __builtin__.print("\n", end="") return r
def print(*args, **kwargs): kwargs.setdefault('file', txtfile) return __builtin__.print(*args, **kwargs)
def print(*a, **kwargs): return __builtin__.print(*a, **kwargs)
def n_print(*args, **kwargs): if("color" in kwargs): kwargs.pop('color') return __builtin__.print(*args, **kwargs)
def print(self): __builtin__.print('attr:', self.attr)
def print(*args, **kwargs): '''custom print function, maybe use for logging later''' __builtin__.print("[GPS - %s] %s" % (tsms2hr(tsms()), args[0]))
def print(*args, **kw): verb = kw.pop('verbose', verbose) if verb: __builtin__.print(*args, **kw)
def print(*args, **kwargs): """custom print function, maybe use for logging later""" __builtin__.print("[CAM - %s] %s " % (tsms2hr(tsms()), args[0]))
def wrp_adder(*args, **kwargs): if not utool.QUIET and utool.VERBOSE: print('[DELETE]: ' + func.func_name) import __builtin__ __builtin__.print('\n' + utool.func_str(func, args, kwargs) + '\n') return func(*args, **kwargs)
def print(str): import __builtin__ if not Quiet: __builtin__.print(str)
def print(*args, **kwargs): '''print(value, ..., sep=' ', end='\n', file=sys.stdout, color=None, background=None, format=None) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. Additional keyword arguments: color: prints values in specified color: grey red green yellow blue magenta cyan white background: prints values on specified color (same as color) format: prints values using specifiend format(s) (can be string or list): bold dark underline reverse concealed''' color = kwargs.pop('color', None) background = kwargs.pop('background', None) formats = kwargs.pop('format', []) if isinstance(formats, basestring): formats = [formats] file = kwargs.get('file', sys.stdout) if (color or background) and file.isatty(): end = kwargs.pop('end', "\n") kwargs['end'] = "" if color: __builtin__.print('\033[%dm' % _colors[color], file=file, end='') if background: __builtin__.print('\033[%dm' % _backgrounds[background], file=file, end='') for format in formats: __builtin__.print('\033[%dm' % _formats[format], file=file, end='') __builtin__.print(*args, **kwargs) __builtin__.print('\033[0m', file=file, end=end) else: __builtin__.print(*args, **kwargs)
def print(msg): __builtin__.print(msg)
def print(*k, **kw): kw = kw.copy() if "flush" in kw: del kw["flush"] return __builtin__.print(*k, **kw)
def pf(*args, **kwargs): kwargs.setdefault('file', stdout) __builtin__.print(*args, **kwargs)
def _dprint(self, *args, **kwargs): """overload print() function to only print when verbose=True.""" if self._verbose: return __builtin__.print(*args, **kwargs)
def display(*args, **kwargs): kwargs.setdefault('file', current_output_port()) return __builtin__.print(*args, **kwargs)
def print(*args, **kwargs): """Enforce the encoding of printed output via :func:`b`; removes the need for some boilerplate when printing to a non-tty. """ __builtin__.print(*map(b, args), **kwargs)
def __init__(self, *output, **codewords): # # ''' Writes something to the output buffer or prints to standard \ output. Examples: >>> buffer = Buffer() >>> Print(native_queue.Queue(), buffer=buffer) # doctest: +ELLIPSIS Object of "Print" with "... >>> queue1 = native_queue.Queue() >>> queue2 = native_queue.Queue() >>> queue1.put('hans') >>> queue2.put('hans') >>> Print( ... queue1, queue2, buffer=buffer, flush=True ... ) # doctest: +ELLIPSIS Object of "Print" with "... >>> Print.default_buffer = Buffer() >>> Print('hans', 'hans again') # doctest: +ELLIPSIS Object of "Print" with "Object of "Buffer" (mem... "hans hans again ".". >>> buffer = Buffer() >>> Print( ... 'hans,', 'peter', end=' and klaus', sep=' ', buffer=buffer ... ) # doctest: +ELLIPSIS Object of "Print" with "Object of "Buffer" (memory buffered...".". >>> buffer # doctest: +ELLIPSIS Object ... (memory buffered) with content "hans, peter and klaus". ''' keywords = { 'replace': self.__class__.replace, 'start': self.__class__.start, 'separator': self.__class__.separator, 'end': self.__class__.end, 'buffer': self.__class__.default_buffer, 'flush': codewords.get('replace', False)} keywords.update(codewords) '''Redirect print output to this buffer.''' self.buffer = keywords['buffer'] output = builtins.list(output) for index, out in builtins.enumerate(output): if builtins.isinstance(out, native_queue.Queue): result = '' while not out.empty(): if index != 0 and keywords['separator']: # # python3.5 # # result += builtins.str(keywords['separator']) # # result += out.get() result += convert_to_unicode( keywords['separator']) result += convert_to_unicode(out.get()) # # output[index] = result elif index == 0: # # python3.5 output[index] = builtins.str(out) output[index] = convert_to_unicode(out) else: # # python3.5 # # output[index] = '%s%s' % (builtins.str( # # keywords['separator'] # # ), builtins.str(out)) output[index] = '%s%s' % (convert_to_unicode( keywords['separator'] ), convert_to_unicode(out)) # # line_replace = '\033[1A\r\033[2K' if keywords['replace'] else '' output = [keywords['start'], line_replace] + output + [keywords['end']] # # python3.5 # # builtins.print( # # *output, sep='', end='', file=keywords['buffer'], # # flush=keywords['flush']) builtins.print(*filter(lambda content: convert_to_string( content ), output), sep='', end='', file=keywords['buffer']) if keywords['flush']: sys.stdout.flush()
from __future__ import division, print_function import __builtin__ import sys try: profile # NoQA __builtin__.print('[common] profiling with kernprof.') except NameError: __builtin__.print('[common] not profiling.') profile = lambda func: func __DEBUG__ = False def init(module_name, module_prefix='[???]', DEBUG=None, initmpl=False): module = sys.modules[module_name] aggroflush = '--aggroflush' in sys.argv if __DEBUG__: __builtin__.print('[common] import %s # %s' % (module_name, module_prefix)) def rrr(): 'Dynamic module reloading' global __DEBUG__ import imp prev = __DEBUG__ __DEBUG__ = False print(module_prefix + ' reloading ' + module_name) imp.reload(module) __DEBUG__ = prev
def init(module_name, module_prefix='[???]', DEBUG=None, initmpl=False): module = sys.modules[module_name] aggroflush = '--aggroflush' in sys.argv if __DEBUG__: __builtin__.print('[common] import %s # %s' % (module_name, module_prefix)) def rrr(): 'Dynamic module reloading' global __DEBUG__ import imp prev = __DEBUG__ __DEBUG__ = False print(module_prefix + ' reloading ' + module_name) imp.reload(module) __DEBUG__ = prev if aggroflush: def print_(msg): sys.stdout.write(msg) sys.stdout.flush() else: def print_(msg): sys.stdout.write(msg) def print(msg): __builtin__.print(msg) #__builtin__.print(module_prefix + msg) def noprint(msg): pass def print_on(): module.print = print module.print_ = print_ def print_off(): module.print = noprint module.print_ = noprint if DEBUG is None: return print, print_, print_on, print_off, rrr, profile if DEBUG: def printDBG(msg): print(module_prefix + ' DEBUG ' + msg) else: def printDBG(msg): pass if initmpl: import matplotlib import multiprocessing backend = matplotlib.get_backend() if multiprocessing.current_process().name == 'MainProcess': print('[common] ' + module_prefix + ' current backend is: %r' % backend) print('[common] ' + module_prefix + ' matplotlib.use(Qt4Agg)') if backend != 'Qt4Agg': matplotlib.use('Qt4Agg', warn=True, force=True) backend = matplotlib.get_backend() print(module_prefix + ' current backend is: %r' % backend) matplotlib.rcParams['toolbar'] = 'toolbar2' matplotlib.rc('text', usetex=False) mpl_keypress_shortcuts = [key for key in matplotlib.rcParams.keys() if key.find('keymap') == 0] for key in mpl_keypress_shortcuts: matplotlib.rcParams[key] = '' #matplotlib.rcParams['text'].usetex = False #for key in mpl_keypress_shortcuts: #print('%s = %s' % (key, matplotlib.rcParams[key])) # Disable mpl shortcuts #matplotlib.rcParams['toolbar'] = 'None' #matplotlib.rcParams['interactive'] = True return print, print_, print_on, print_off, rrr, profile, printDBG
def line_print(*args,**kwargs): ln = inspect.currentframe().f_back.f_lineno return builtins.print("Line: [%d]"%(ln),*args, **kwargs)