コード例 #1
0
    def excepthook(exc_type, exc_value, exc_traceback):
        try:
            # On Python 2, exceptions have no __cause__, __context__ or __supress_context__.
            if getattr(exc_value, "__cause__", None) is not None:
                excepthook(exc_value.__cause__.__class__, exc_value.__cause__,
                           exc_value.__cause__.__traceback__)
                console.set_color(0.75, 0.0, 0.0)
                print()
                print(
                    u"The above exception was the direct cause of the following exception:"
                )
                print()
            elif getattr(
                    exc_value, "__context__",
                    None) is not None and not exc_value.__suppress_context__:
                excepthook(exc_value.__context__.__class__,
                           exc_value.__context__,
                           exc_value.__context__.__traceback__)
                console.set_color(0.75, 0.0, 0.0)
                print()
                print(
                    u"During handling of the above exception, another exception occurred:"
                )
                print()

            _excepthook(exc_type, exc_value, exc_traceback)
        except Exception as err:
            traceback.print_exc()
        finally:
            set_color("default_text")
コード例 #2
0
    def console(self, webview_index=0):
        webview = WKWebView.webviews[webview_index]
        theme = WKWebView.Theme.get_theme()

        print('Welcome to WKWebView console.')
        print('Evaluate javascript in any active WKWebView.')
        print('Special commands: list, switch #, load <url>, quit')
        console.set_color(*ui.parse_color(theme.tint)[:3])
        while True:
            value = input('js> ').strip()
            self.console_view.history().insertObject_atIndex_(
                ns(value + '\n'), 0)
            if value == 'quit':
                break
            if value == 'list':
                for i in range(len(WKWebView.webviews)):
                    wv = WKWebView.webviews[i]
                    print(i, '-', wv.name, '-', wv.eval_js('document.title'))
            elif value.startswith('switch '):
                i = int(value[len('switch '):])
                webview = WKWebView.webviews[i]
            elif value.startswith('load '):
                url = value[len('load '):]
                webview.load_url(url)
            else:
                print(webview.eval_js(value))
        console.set_color(*ui.parse_color(theme.default_text)[:3])
コード例 #3
0
def set_forecast_font():
    if DARK_MODE:
        console.set_color(1, 1, 1)
    else:
        console.set_color(0, 0, 0)

    console.set_font("Menlo-Regular", TABLE_FONTSIZE)
コード例 #4
0
def download_img(url):
    global down_count, dp_count, img_num, name
    down_count = down_count + 1
    dp_count = dp_count + 1
    console.set_color(.2, .8, .2)
    dp = '□' * 10
    status = '下载中'
    if dp_count > 9:
        dp_count = 0
    elif down_count == img_num:
        console.set_color(1, 0, .8)
        dp_count = 10
        status = '完成!'

    else:
        pass
    dp = dp.replace('□', '■', dp_count)
    img_name = url.split(',')[0] + '.jpg'
    url = url.split(',')[1]
    #img_name = url.split('/')[-1]
    sys.stdout.write('\r' + status + dp + '(' + str(down_count) + '/' +
                     str(img_num) + ')')
    sys.stdout.flush()
    img_data = requests.get(url, timeout=7).content
    name += 1
    with open(folder_path + '/' + img_name, 'wb') as handler:
        handler.write(img_data)
コード例 #5
0
def download_img(url):
    global down_count, dp_count, img_num
    down_count = down_count + 1
    dp_count = dp_count + 1
    console.set_color(.2, .8, .2)
    dp = '□' * 10
    status = '下载中'
    if dp_count > 9:
        dp_count = 0
    if down_count == img_num:
        console.set_color(1, 0, .8)
        dp_count = 10
        status = '完成!'
    dp = dp.replace('□', '■', dp_count)
    sys.stdout.write('\r' + status + dp + '(' + str(down_count) + '/' +
                     str(img_num) + ')')
    sys.stdout.flush()
    header = {'Referer': 'https://www.nvshens.com'}
    img_data = requests.get(url, headers=header, timeout=20).content
    if name_prefix:
        img_name = name_prefix + '-' + url.split('/')[-1] + '.jpg'
    else:
        img_name = url.split('/')[-1] + '.jpg'
    with open(folder_path + '/' + img_name, 'wb') as handler:
        handler.write(img_data)
コード例 #6
0
def prepare():
    global Name
    console.set_font('Academy Engraved LET', 16)
    console.set_color(.23, 1.0, .45)
    Name = input('Name your pet! ')
    console.set_color(.0, .86, 1.2)
    console.set_font('Academy Engraved LET', 16)
コード例 #7
0
def cpoint(loc=""):
    loc = loc.replace("./", "")
    while 1:
        console.write_link("msf", "")
        if loc == "":
            sys.stdout.write(" ")
        else:
            loco = loc.split("/")
            sys.stdout.write(" %s(" % (loco[0]))
            console.set_color(1, 0, 0)
            sys.stdout.write("%s" % (loco[1]))
            console.set_color(1, 1, 1)
            sys.stdout.write(") ")
        try:
            data = raw_input("> ")
        except:
            print
            data = ""
            pass
        if data == "clear":
            console.clear()
        if data.startswith("use ") and len(data) > 4:
            data = data[4:]
            if data in sets:
                try:
                    cpoint(fdir(sets[data]))
                except:
                    pass
            else:
                try:
                    cpoint(fdir(data))
                except:
                    pass
        if data == "back":
            break
        if data == "exit":
            exit()
        if data == "banner":
            unilogo()
        meta_help(data, loc)
        if data.startswith("size ") and len(data) > 4:
            data = data[4:]
            try:
                console.set_font("Menlo", int(data))
            except:
                pass
        if data == "size":
            console.set_font("Menlo", 9.5)
        if data.startswith("remove ") and len(data) > 6:
            data = data[7:]
            try:
                if data in sets:
                    t = data + " => " + sets.get(data)
                    sets.pop(data)
                    var.remove(t)
                    print "Removed Values For \"%s\"" % data
            except Exception as e:
                print e
                pass
コード例 #8
0
def print_banner():
    console.clear()
    console.set_color(1, 0, 0)
    console.set_font("Menlo-Bold", 30)
    print("Insta Fortune!", end="")
    print("=" * 14)
    console.set_color(1, 1, 1)
    console.set_font()
コード例 #9
0
 def concole_print(self, msg, color=[]):
     if color:
         for i, j in zip(msg, color):
             console.set_color(*j)
             print(i, end='')
         print()
         console.set_color()
     else:
         print(''.join(msg))
コード例 #10
0
def backup(path=backpath, dst=dstpath):
    now = datetime.datetime.now()
    ymd = now.strftime('%Y-%m-%d')
    number = 1
    if not os.path.exists(dstpath):
        os.makedirs(dstpath)
    while True:
        basename = 'Backup' + ymd + '_' + str(number) + '.zip'
        zipFilename = os.path.join(dst + basename)
        if not os.path.exists(zipFilename):
            break
        number += 1
    a, b = 0, 0
    for f in os.listdir(path):
        if os.path.isdir(path + f):
            a += 1
        else:
            b += 1
    dispath = path.replace(os.path.expanduser('~'), '~')
    console.alert('备份{}'.format(dispath), '{}个文件夹和{}个文件,可能需要几秒钟'.format(a, b),
                  '确定')
    backupzip = zipfile.ZipFile(zipFilename, 'w')
    n = 1
    for foldername, subfolders, filenames in os.walk(path):
        #console.hud_alert('备份第{}个文件夹'.format(n), '1')
        if Trashpath in foldername and EXCLUDE_Trash:
            continue
        #print('备份第{}个子文件夹:{}'.format(n,foldername.replace(os.path.expanduser('~'),'~'))+'\n')
        backupzip.write(foldername)
        n += 1
        for filename in filenames:
            if filename.startswith('Backup') and filename.endswith('.zip'):
                continue
            backupzip.write(os.path.join(foldername, filename))
    backupzip.close()
    console.hud_alert('备份完成!开始进行HTTP服务器部署...', '3')

    os.chdir(dstpath)
    local_url = 'http://localhost:{}/{}'.format(PORT,
                                                os.path.basename(zipFilename))
    wifi_url = 'http://{}:{}/{}'.format(get_ip_address(), PORT,
                                        os.path.basename(zipFilename))
    server = HTTPServer(('', PORT), SimpleHTTPRequestHandler)
    console.clear()
    print('① 点击下面链接选择在Safari打开备份文件,再分享到其他App:')
    console.set_color(0, 0, 1)
    console.write_link(local_url + '\n', 'safari-' + local_url)
    console.set_color(1, 1, 1)
    print('\n② 如果想在局域网中其他设备访问该备份,请在其他设备中输入以下链接:')
    print(wifi_url)
    print('\n====\n完成分享后请在 console 中点停止.')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        server.socket.close()
        print('服务器终止')
コード例 #11
0
ファイル: print_agenda.py プロジェクト: iansoper/TodoFlow
def hcs(font_size=None, color=None):
    if font_size:
        console.set_font('', font_size)
    else:
        console.set_font()
    if color:
        console.set_color(*color)
    else:
        console.set_color()
コード例 #12
0
def console_color(r, g, b):
    '''
    Sets the console output to the specified color
    Changes it back to black afterwards
    '''
    set_color(r, g, b)
    try:
        yield
    finally:
        set_color(0, 0, 0)
コード例 #13
0
	def animate(self):
		run = "[ %s ] "%self.header
		runu = run.upper()
		for a in range(1):
			for x in range(len(run)):
				s = "\r"+run[0:x]+runu[x]+run[x+1:]
				sys.stdout.write(s)
				sys.stdout.flush()
				time.sleep(0.1)
		console.set_color()
コード例 #14
0
def terminal(text=False, inp=False):
    console.set_color(0.0, 0.3, 0.8)
    sys.stdout.write("root@elliot:$ ")
    console.set_color()
    if text == False:
        return raw_input()
    else:
        if inp:
            return raw_input(text)
        else:
            print text
コード例 #15
0
ファイル: system.py プロジェクト: teneen/blackmamba
 def new_func(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception:
         if console:
             console.set_color(1, 0, 0)
         print(traceback.format_exc())
         print('Please, file an issue at {}'.format(
             'https://github.com/zrzka/blackmamba/issues'))
         if console:
             console.set_color()
コード例 #16
0
    def print_danmu(self, danmu_msg: dict):
        if not self.danmu_control:
            return
        danmu_msg_info = danmu_msg['info']

        list_msg = []
        list_color = []
        if danmu_msg_info[7] == 3:
            # print('舰', end=' ')
            list_msg.append('⚓️ ')
            list_color.append([])
        else:
            if danmu_msg_info[2][3] == 1:
                if danmu_msg_info[2][4] == 0:
                    list_msg.append('爷 ')
                    list_color.append(self.dic_color['others']['vip'])
                else:
                    list_msg.append('爷 ')
                    list_color.append(self.dic_color['others']['svip'])
            if danmu_msg_info[2][2] == 1:
                list_msg.append('房管 ')
                list_color.append(self.dic_color['others']['admin'])

            # 勋章
            if danmu_msg_info[3]:
                list_color.append(
                    self.dic_color['fans-level'][f'fl{danmu_msg_info[3][0]}'])
                list_msg.append(
                    f'{danmu_msg_info[3][1]}|{danmu_msg_info[3][0]} ')
            # 等级
            if not danmu_msg_info[5]:
                list_color.append(
                    self.dic_color['user-level'][f'ul{danmu_msg_info[4][0]}'])
                list_msg.append(f'UL{danmu_msg_info[4][0]} ')

        list_msg.append(danmu_msg_info[2][1] + ':')
        try:
            if danmu_msg_info[2][7]:
                list_color.append(self.hex_to_rgb_percent(
                    danmu_msg_info[2][7]))
            else:
                list_color.append(self.dic_color['others']['default_name'])
        except IndexError:
            print("# 小电视降临本直播间")
            list_color.append(self.dic_color['others']['default_name'])

        list_msg.append(danmu_msg_info[1])
        list_color.append([])
        for i, j in zip(list_msg, list_color):
            console.set_color(*j)
            print(i, end='')
        print()
        console.set_color()
def ldImg(imgPath,folderPath='Images',urlPath='Null'):
	try:
		if folderPath: folderPath+="/"
		if not os.path.exists(folderPath[:-1]): os.mkdir(folderPath[:-1])
		url = urlopen(urlPath)
		with open(folderPath+imgPath+'.png', "wb") as output:
			output.write(url.read())
		return os.getcwd()+'/'+folderPath+imgPath
	except:
		console.set_color(1,0,0)
		print '\nERROR: Download failed.'
		sys.exit()
コード例 #18
0
ファイル: log.py プロジェクト: teneen/blackmamba
def _log(level, *args, **kwargs):
    if _level > level:
        return

    color = _COLORS.get(level, None)
    if console and color:
        console.set_color(*color)

    print(*args, **kwargs)

    if console and color:
        console.set_color()
コード例 #19
0
ファイル: apdosFEED.py プロジェクト: hotnix87/APDOS
def dos():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(4)
    try:
        s.connect((host, int(port)))
        s.send("GET /%s HTTP/1.1\r\n" % message)
        s.sendto("GET /%s HTTP/1.1\r\n" % message, (ip, port))
        s.send("GET /%s HTTP/1.1\r\n" % message)
    except socket.error, msg:
        console.set_color(255, 0, 0)
        print("-[Connection Failed]-=@=--+-")
        console.set_color()
コード例 #20
0
ファイル: CodeBlue.py プロジェクト: Patronics/networking
	def did_connect_peripheral(self, p):
		p.discover_services()
		print ""
		for i in range(4):
			sys.stdout.write("\rSending Payload" + "." * i)
			time.sleep(1)
		time.sleep(2)
		sys.stdout.write("\nDevice Status: ")
		console.set_color(1,0,0)
		console.set_font('Chalkduster',14)
		sys.stdout.write("PWNED\n")
		console.set_font()
		console.set_color()
コード例 #21
0
 def print_result(self):
     print(self.result_count, end="\n\n")
     if not on_phone:
         for i in self.results:
             print(f"{i['title']}\n{i['caption']}\n{i['link']}\n\n")
     else:
         for i in self.results:
             console.set_color(.0, .81, .23)
             print(i['title'])
             console.set_color(0, 0, 0)
             print(i['caption'])
             print(i['link'])
             print('\n')
コード例 #22
0
def credits():
    """
	Copyright (c) Romap v3.7.6 - SavSec
	"""
    console.set_color(1, 1, 0)
    print "   _ __ ___  _ __ ___   __ _ _ __ "
    print "  | '__/ _ \| '_ ` _ \ / _` | '_ \ "
    print "  | | | (_) | | | | | | (_| | |_)| "
    print "  |_|  \___/|_| |_| |_|\__,_| .__/"
    print "                            |_|   "
    console.set_color()
    print " " * 2 + "Starting romap on %s\n" % (socket.gethostname())
    time.sleep(1)
コード例 #23
0
ファイル: shell.py プロジェクト: tomasgonz/datascrapper2
	def __init__(self):
		cmd.Cmd.__init__(self)

		self.name = "Scrapper"
		# this should place sticky text on the top right side of the shell
		# you can change this text by calling sticker() from a commandthat appears in the top left of the shell
		self.header = """Welcome to Scrapper, a console application focused on data. Built by Tomas Gonzalez."""

		init()
		
		console.set_color(1,0,0)

		print(self.header)
コード例 #24
0
def config_consola(localizacao):
    '''
    Sets console font size and color for Pythonista on iOS
    '''
    console.clear()
    console.set_font("Menlo-Bold", HEADER_FONTSIZE)

    if DARK_MODE:
        console.set_color(0.5, 0.8, 1)
    else:
        console.set_color(0.2, 0.5, 1)

    line_length = 32
    if len(localizacao + __app_name__ + ' ') > line_length:
        str_title = "{}\n({})".format(__app_name__, localizacao)
    else:
        str_title = "{} ({})".format(__app_name__, localizacao)

    print(str_title)
    console.set_font("Menlo-Regular", 6.7)

    if DARK_MODE:
        console.set_color(0.7, 0.7, 0.7)
    else:
        console.set_color(0.5, 0.5, 0.5)
    print(f'{__copyright__}, {__license__}\n\n')
コード例 #25
0
 def did_connect_peripheral(self, p):
     print('did_connect_peripheral({})'.format(p.name))
     p.discover_services()
     print("")
     for i in range(4):
         sys.stdout.write("\rConnecting" + "." * i)
         time.sleep(1)
     time.sleep(2)
     sys.stdout.write("\nDevice Status: ")
     console.set_color(1, 0, 0)
     console.set_font('Chalkduster', 14)
     sys.stdout.write("Connected\n")
     console.set_font()
     console.set_color()
コード例 #26
0
def print_stats():
    console.set_font("Menlo-Bold", 14)
    print('Всего коментариев: ')
    console.set_font()
    print(len(all_comments))
    console.set_font("Menlo-Bold", 14)
    print('Хотят открытку: ')
    console.set_font()
    print(len(comments))
    console.set_font("Menlo-Bold", 14)
    console.set_color(1, 0, 0)
    print('-' * 14)
    console.set_color(1, 1, 1)
    console.set_font()
コード例 #27
0
def raw_input2(value="", end="", u=False, c=False):
	sys.stdout.write(value)
	data = getpass.getpass("")
	if data == "\n":
		data = ""
	if c:
		if sys.platform == "ios":
			console.set_color()
		else:
			sys.stdout.write(Style.RESET_ALL)
	if u:
		sys.stdout.write(data.upper())
	else:
		sys.stdout.write(data)
	sys.stdout.write(end)
	return data
コード例 #28
0
	def task(self, item):
		if item.has_tag('working'):
			console.set_color(0.00, 0.50, 0.50)
		elif item.has_any_tags(['done', 'blocked']):
			console.set_color(0.50, 0.50, 0.50)
		elif item.has_tag('next'):
			console.set_color(0.00, 0.50, 1.00)
		elif item.has_tag('due'):
			console.set_color(1.00, 0.00, 0.50)
コード例 #29
0
def get_size():
	if appex.is_running_extension():
		path = appex.get_file_path()
		if not os.path.exists(path):
			raise Exception('文件路径不存在')
		if os.path.isfile(path):
			size = os.path.getsize(path)
		else:
			size = folder_size(path)
		console.clear()
		console.set_color(0.3,0.3,1)
		console.set_font('Menlo',20)
		print('文件名称: ' + path.split('/')[-1])	
		print('文件大小: ' + actualSize(size))
		print('占用空间: ' + capacitySize(size))
	else:
		console.hud_alert('请在分享扩展中打开本脚本', 'error', 2)
コード例 #30
0
ファイル: URSE.py プロジェクト: fortify24x7/UltimateRSE
def urse_logo():
    if sys.platform == "ios":
        import console
        console.set_color()
        print
        if int(os.uname()[4][6]) >= 7:
            console.set_font("Menlo", 14.9)
        else:
            console.set_font("Menlo", 12.6)
        print "     Ultimate Remote Shell Execution"
        lastc = "b"
        for _ in logo:
            time.sleep(0.0005)
            if _ != "U":
                if lastc != "w":
                    console.set_color(1, 0, 0)
                    lastc = "w"
                if _ == " ":
                    sys.stdout.write(_)
                elif _ == "\n" or _ == "\t":
                    sys.stdout.write(_)
                else:
                    sys.stdout.write("M")
            else:
                if lastc != "b":
                    console.set_color(1, 1, 1)
                    lastc = "b"
                sys.stdout.write(_)
        print "\n"
        console.set_color()
        print " -= Version -- [" + " " * (
            (19 - len(version)) / 2) + version + " " * (
                (19 - len(version)) / 2) + "] =-"
        print " -= Edition -- [" + " " * (
            (19 - len(edition)) / 2) + edition.upper() + " " * (
                (19 - len(edition)) / 2) + "] =-"
        print " -= Address -- [" + " " * (
            (19 - len(address)) / 2) + address + " " * (
                (18 - len(address)) / 2) + "] =-"
        print
        console.set_font("Menlo", 12.5)
    else:
        print
        print logo
        print
        print " -= Version -- [ " + " " * (
            (15 - len(version)) / 2) + version + " " * (
                (15 - len(version)) / 2) + " ] =-"
        print " -= Edition -- [ " + " " * (
            (15 - len(edition)) / 2) + edition.upper() + " " * (
                (15 - len(edition)) / 2) + " ] =-"
        print " -= Address -- [ " + " " * (
            (15 - len(address)) / 2) + address + " " * (
                (14 - len(address)) / 2) + " ] =-"
        print
コード例 #31
0
ファイル: __init__.py プロジェクト: hex96/display_py
    def display(self):
        console.clear()

        start_time = datetime.datetime.now()

        for i in range(len(self.grid)):
            for j in range(len(self.grid[i])):
                r = self.grid[i][j][1]
                g = self.grid[i][j][2]
                b = self.grid[i][j][3]

                console.set_color(r, g, b)

                print(self.grid[i][j][0], end='')
                console.set_color()

            print()

        return datetime.datetime.now() - start_time
コード例 #32
0
ファイル: highlight.py プロジェクト: TotKindGott/formatlib
def highlight(text, color, inline=True, alignment='left', width=0, fill=' '):
    """
  Accepts following arguments:
      text (required) - string to output to console
      color (required) - text output color
      inline (default=True) - creates a new line after output
      alignment (default='left') - can be also 'right' or 'center'
      width (default=0) - text justification value
  """

    # Does not print any whitespace around the string passed as argument

    default_color = colors['white']

    def revert_colors(color):
        console.set_color(color[0], color[1], color[2])

    if color in colors.keys():
        console.set_color(colors[color][0], colors[color][1], colors[color][2])
    elif isinstance(color, tuple):
        # unpack the set of RGB values
        if len(color) == 3:
            console.set_color(color[0], color[1], color[2])
        else:
            revert_colors(default_color)
    else:
        revert_colors(default_color)

    if alignment == 'right':
        alignment = '>'
    elif alignment == 'center':
        alignment = '^'
    else:
        alignment = '<'

    style = str('{:' + fill + alignment + str(width) + '}')

    sys.stdout.write(style.format(text))

    revert_colors(default_color)

    if inline == False:
        print ''  # create a new line
コード例 #33
0
 def emit(self, record):
     if record.levelno == logging.DEBUG:
         console.set_color(console.FOREGROUND_MAGENTA)
     if record.levelno == logging.WARNING:
         console.set_color(console.FOREGROUND_YELLOW)
     if record.levelno == logging.ERROR:
         console.set_color(console.FOREGROUND_RED)
     if record.levelno == logging.CRITICAL:
         console.set_bright_color(console.FOREGROUND_RED)
     line = self.format(record)
     print(line)
     console.set_color()
コード例 #34
0
ファイル: print_objc.py プロジェクト: Subject22/objc_hacks
def print_methods(clsname,print_private=False):
   cls=ObjCClass(clsname)
   console.set_color(1,0,0)
   print(clsname)
   print('Class Methods______')
   console.set_color(0,0,0)
   m=get_class_methods(cls)
   print('\n'.join([(k[1]+' ' +k[0]+'( '+', '.join(k[2])+' )') for k in m if not k[0].startswith(b'_')]))
   if print_private:
         print('\n'.join([(k[1]+' ' +k[0]+'( '+', '.join(k[2])+' )') for k in m if k[0].startswith(b'_')]))
   console.set_color(1,0,0)
   print('_______Instance Methods______')
   console.set_color(0,0,0)
   m=get_methods(cls)
   print('\n'.join([(k[1]+'\t' +k[0]+'( '+', '.join(k[2])+' )') for k in m if not k[0].startswith(b'_')]))
   if print_private:
         print(b'\n'.join([(k[1]+'\t' +k[0]+b'( '+b', '.join(k[2])+b' )') for k in m if k[0].startswith(b'_')]))
コード例 #35
0
 def displayhook(obj):
     # Uncomment the next line if you want None to be "visible" like any other object.
     #"""
     if obj is None:
         return
     #"""
     
     try:
         builtins.Out
     except AttributeError:
         builtins.Out = []
     
     builtins._ = obj
     builtins.Out.append(obj)
     console.set_color(0.0, 0.5, 0.0)
     print(u"Out[{}]".format(len(builtins.Out)-1), end=u"")
     console.set_color(0.2, 0.2, 0.2)
     print(u" = ", end=u"")
     console.set_color(0.33, 0.57, 1.0)
     print(repr(obj))
     console.set_color(0.2, 0.2, 0.2)
コード例 #36
0
 def excepthook(exc_type, exc_value, exc_traceback):
     try:
         # On Python 2, exceptions have no __cause__, __context__ or __supress_context__.
         if getattr(exc_value, "__cause__", None) is not None:
             excepthook(exc_value.__cause__.__class__, exc_value.__cause__, exc_value.__cause__.__traceback__)
             console.set_color(0.75, 0.0, 0.0)
             print()
             print(u"The above exception was the direct cause of the following exception:")
             print()
         elif getattr(exc_value, "__context__", None) is not None and not exc_value.__suppress_context__:
             excepthook(exc_value.__context__.__class__, exc_value.__context__, exc_value.__context__.__traceback__)
             console.set_color(0.75, 0.0, 0.0)
             print()
             print(u"During handling of the above exception, another exception occurred:")
             print()
         
         _excepthook(exc_type, exc_value, exc_traceback)
     except Exception as err:
         traceback.print_exc()
     finally:
         console.set_color(0.2, 0.2, 0.2)
コード例 #37
0
def clear():
	console.clear()
	console.set_font("Futura-Medium", 20)
	console.set_color(0.40, 0.40, 0.40)
コード例 #38
0
images = []
	
while 1:
	img = photos.pick_image(show_albums=True)
	if img:
		images.append(img)
	else:
		break

count = len(images)

clear()

if count == 0:
	console.set_color(0.50, 0.00, 0.00)
	print("No images selected.")
	sys.exit()

print("Merging {0} images...".format(count))

width, height = images[0].size
if width in retina_pixels:
	width, height = map(lambda a: a/2, (width, height))

result = Image.new("RGBA", (width*count + margin*(count-1), height), background)

for i, img in enumerate(images):
	shot = img.resize((width, height), Image.ANTIALIAS)
	result.paste(shot, (width*i+margin*i, 0))
コード例 #39
0
ファイル: Webclip Creator.py プロジェクト: c0ns0le/Pythonista
payload_name = 'Pythonista Script'

console.alert('Please select an icon', '', 'Ok')
png_data = StringIO()
photos.pick_image().save(png_data, format='PNG')
png_str = base64.b64encode(png_data.getvalue())
png_data.close()

UUID1 = uuid.uuid4()
UUID2 = uuid.uuid4()

mobile_config_str = base_mobileconfig % (png_str, icon_label, UUID1, UUID1, urllib.quote(script_name), arg_str, payload_name, UUID2, script_name, UUID2)

clipboard.set('http://%s:%s/webclip.mobileconfig' % (ip, port))

console.clear()
console.set_font('Futura', 16)
console.set_color(0.2, 0.2, 1)
print "Safari will open automatically. Alternatively, you can open Safari manually and paste in the URL on your clipboard.\n"
console.set_font()
console.set_color()

my_httpd = NicerHTTPServer((ip, port), MobileConfigHTTPRequestHandler)
print "Serving HTTP on %s:%s ..." % (ip, port)

webbrowser.open('safari-http://%s:%s/webclip.mobileconfig' % (ip, port))
my_httpd.serve_forever()

print "\n*** Webclip installed! ***"

コード例 #40
0
	def ttask(self, item):
		self.task(item)
		print(indent * item.indent_level + '- ' + item.text)
		console.set_color()
コード例 #41
0
	def project(self, item):
		console.set_color(0.00, 0.00, 0.00)
		print(indent * item.indent_level + item.text + ':')
		console.set_color()
コード例 #42
0
ファイル: helpers.py プロジェクト: davidseibert/korean
 def configure_console(self):
     if PYTHONISTA:
         console.set_color(*self.CONSOLE_COLOR)
コード例 #43
0
# Check the status of the Apple Dev Center systems.
# Offline systems appear in orange
# Online systems appear in black
#
# Author: Nicolas HOIBIAN | @nico_h | www.niconomicon.net
# License: Creative Common By-NC-SA
#
# @viticci on twitter created a version that uses the Pythonista notification module for timely reminders:
# http://www.macstories.net/linked/check-dev-center-status-from-ios-with-pythonista/
#
# url fetching activity indicator courtesy of @fcrespo82 on twitter
#https://gist.github.com/fcrespo82/5b9b35bc8a0a62c7ec1a

console.clear()
console.set_font("Futura", 16)
console.set_color(0, 0, 0)
print "Fetching DevCenter status"
print datetime.now().strftime("%Y/%m/%d %H:%M:%S (local time)")
url="https://developer.apple.com/support/system-status/"
console.show_activity()
resp = requests.get(url)
console.hide_activity()

html_doc = resp.text
soup = BeautifulSoup(html_doc)

down = 0
up = 0
# Data Last Updated on apple server
for h2 in soup.find_all("h2"):
  print "Data Last", h2.text
# by Logan G.
#
# Sorry for the sloppy, uncommented code.
# I started it at 2am and don't care
# enough to make it more understandable.
# # # # # # # # # # # # # # # # # # # # #


import console, sound, random, scene, ui, speech, webbrowser, string, os, sys
from urllib import urlopen
from scene import *
from PIL import Image


console.clear()
console.set_color(0.2, 0.2, 0.2)
console.set_font('Helvetica', 14)


folderPath = 'ImageFiles/Imported/'
imgPath='Insults'
urlPath='http://i.imgur.com/q4UXODX.png'

def ldImg(imgPath,folderPath='Images',urlPath='Null'):
	try:
		if folderPath: folderPath+="/"
		if not os.path.exists(folderPath[:-1]): os.mkdir(folderPath[:-1])
		url = urlopen(urlPath)
		with open(folderPath+imgPath+'.png', "wb") as output:
			output.write(url.read())
		return os.getcwd()+'/'+folderPath+imgPath
コード例 #45
0
ファイル: localio.py プロジェクト: vinyldarkscratch/Fur
def makeColor(color):
    global styles
    try:  # If styles is greater than 20, reset...
        if len(styles) > 20:
            styles = colorama.Fore.WHITE
        styles = colorama.Fore.WHITE
    except:
        pass  # ...or pass if on iOS
    if color == "red":
        try:
            console.set_color(1.0, 0.0, 0.0)
        except:
            styles += colorama.Fore.RED
    elif color == "green":
        try:
            console.set_color(0.2, 0.8, 0.2)
        except:
            styles += colorama.Fore.GREEN
    elif color == "blue":
        try:
            console.set_color(0.0, 0.0, 1.0)
        except:
            styles += colorama.Fore.CYAN
    elif color == "yellow":
        try:
            console.set_color(0.6, 0.6, 0.1)
        except:
            styles += colorama.Fore.YELLOW
    elif color == "darkblue":
        try:
            console.set_color(0.6, 0.6, 1.0)
        except:
            styles += colorama.Fore.BLUE
    elif color == "magenta":
        try:
            console.set_color(1.0, 0.2, 1.0)
        except:
            styles += colorama.Fore.MAGENTA
    elif color == "reset":
        try:
            console.set_color(0.2, 0.2, 0.2)
            console.set_font()
        except:
            styles += colorama.Fore.WHITE
    elif color == "random":
        try:
            console.set_color(random.random(), random.random(), random.random())
        except:
            list = [
                colorama.Fore.RED,
                colorama.Fore.GREEN,
                colorama.Fore.YELLOW,
                colorama.Fore.BLUE,
                colorama.Fore.MAGENTA,
                colorama.Fore.CYAN,
                colorama.Fore.WHITE,
            ]
            styles += random.choice(list)
    elif color == "bold":
        try:
            console.set_font("Helvetica", 32.0)
        except:
            pass
    else:
        print("Color input was invalid: %s." % color)
    if styles and config.color:
        outputfd.write(styles)
        outputfd.flush()
コード例 #46
0
ファイル: print_agenda.py プロジェクト: iansoper/TodoFlow
def print_title(title, color):
    console.set_font(size=32)
    console.set_color(*color)
    print title
    console.set_font()
    console.set_color()
コード例 #47
0
 def _excepthook(exc_type, exc_value, exc_traceback):
     console.set_color(0.75, 0.0, 0.0)
     print(u"Traceback (most recent call last):")
     
     for filename, lineno, funcname, text in traceback.extract_tb(exc_traceback):
         
         console.set_color(0.2, 0.2, 0.2)
         print(u"\tFile ", end=u"")
         console.set_color(0.81, 0.32, 0.29)
         write_filename(filename)
         
         console.set_color(0.2, 0.2, 0.2)
         print(u", line ", end=u"")
         console.set_color(0.15, 0.51, 0.84)
         print(lineno, end=u"")
         
         console.set_color(0.2, 0.2, 0.2)
         print(u", in ", end=u"")
         console.set_color(0.13, 0.46, 0.49)
         print(funcname, end=u"")
         
         console.set_color(0.2, 0.2, 0.2)
         print(u":")
         
         console.set_color(0.2, 0.2, 0.2)
         if isinstance(text, bytes):
             text = text.decode(u"utf-8", u"replace")
         print(u"\t\t" + (text or u"# Source code unavailable"))
         print()
     
     if issubclass(exc_type, SyntaxError):
         console.set_color(0.2, 0.2, 0.2)
         print(u"\tFile ", end=u"")
         console.set_color(0.81, 0.32, 0.29)
         write_filename(exc_value.filename)
         
         console.set_color(0.2, 0.2, 0.2)
         print(u", line ", end=u"")
         console.set_color(0.15, 0.51, 0.84)
         print(exc_value.lineno, end=u"")
         
         console.set_color(0.2, 0.2, 0.2)
         print(u":")
         
         if exc_value.text is None:
             console.set_color(0.75, 0.0, 0.0)
             print(u"\t\t# Source code unavailable")
         else:
             etext = exc_value.text
             if isinstance(etext, bytes):
                 etext = etext.decode(u"utf-8", u"replace")
             console.set_color(0.2, 0.2, 0.2)
             print(u"\t\t" + etext[:exc_value.offset], end=u"")
             console.set_color(0.75, 0.0, 0.0)
             print(u"\N{COMBINING LOW LINE}" + etext[exc_value.offset:].rstrip())
     
     console.set_color(0.43, 0.25, 0.66)
     print(exc_type.__module__, end=u"")
     console.set_color(0.2, 0.2, 0.2)
     print(u".", end=u"")
     console.set_color(0.13, 0.46, 0.49)
     print(getattr(exc_type, "__qualname__", exc_type.__name__), end=u"")
     
     msg = exc_value.msg if issubclass(exc_type, SyntaxError) else str(exc_value)
     
     if msg:
         console.set_color(0.2, 0.2, 0.2)
         print(u": ", end=u"")
         console.set_color(0.75, 0.0, 0.0)
         print(msg, end=u"")
     
     console.set_color(0.2, 0.2, 0.2)
     print()
コード例 #48
0
ファイル: Shell.py プロジェクト: c0ns0le/Pythonista
def print_in_color(color_name, msg):
	color = get_color(color_name)
	if color:
		console.set_color(*color)
	print msg
	console.set_color()
コード例 #49
0
ファイル: printf.py プロジェクト: D3ee/bilibili-live-tools
 def hex_print(self, hex_str, str, end=' '):
     # print(str)
     color = webcolors.hex_to_rgb_percent(hex_str)
     console.set_color(*[float(i.strip('%'))/100.0 for i in color])
     print(str, end=end)
     console.set_color()
コード例 #50
0
ファイル: Zen.py プロジェクト: c0ns0le/Pythonista
#Suppress the output while importing 'this':
prev_out = sys.stdout
sys.stdout = StringIO()
import this
sys.stdout = prev_out
console.clear()

#Decode the 'Zen of Python' text and split to a list of lines:
decoder = codecs.getdecoder('rot_13')
text = decoder(this.s)[0]
lines = text.split('\n')

#Print the title (first line):
console.set_font('Futura', 22)
console.set_color(0.2, 0.2, 0.2)
print lines[0]

#Print the other lines in varying colors:
hue = 0.45
for line in lines[1:]:
	r, g, b = hsv_to_rgb(hue, 1.0, 0.8)
	console.set_color(r, g, b)
	console.set_font('Futura', 16)
	print line
	hue += 0.02

#Reset output to default font and color:
console.set_font()
console.set_color()
コード例 #51
0
ファイル: printf.py プロジェクト: D3ee/bilibili-live-tools
 def rgb_print(self, rgb_str, str, end=' '):
     #print(str)
     color = webcolors.rgb_to_rgb_percent(map(int,rgb_str.split()))
     console.set_color(*[float(i.strip('%'))/100.0 for i in color])
     print(str, end=end)
     console.set_color()
コード例 #52
0
ファイル: debug-iOS.py プロジェクト: vinyldarkscratch/Fur
try:
	from Fur import * #Imports Fur
	init() #runs the game start function
except:
	import console, traceback
	
	console.set_color(0, 0.8, 0) #sets the color to green
	print("Type: "+str(sys.exc_info()[0])) #prints the type of exception
	
	console.set_color(0.8, 0, 0) #sets the color to red
	print("\n\n"+traceback.format_exc()) #prints error information