Best Python code snippet using Testify_python
terminal.py
Source:terminal.py
1#!/usr/bin/env python32# Make sure the right versions are loaded3import gi4gi.require_version('Gtk', '3.0')5gi.require_version('Vte', '2.91')6gi.require_version('Gdk', '3.0')7from gi.repository import Gtk, GLib, Vte, Gdk, Gio8from os import environ9import time10# Reference: https://lazka.github.io/pgi-docs/Vte-2.91/classes/Terminal.html11class Terminal(Vte.Terminal):12 def __init__(self):13 super(Terminal, self).__init__()14 # Signals15 self.connect_after('child-exited', self.on_child_exited)16 self.connect("key_press_event", self.on_key_press)17 self.connect('contents-changed', self.on_contents_changed)18 # Properties19 self.pause_logging = False20 self.log_file = None21 self.enable_copy_paste = True22 self.set_scroll_on_output(True)23 self.set_input_enabled(True)24 self._cancellable = Gio.Cancellable()25 self._last_row = 026 self._cmd_is_running = False27 28 # Colors29 fg = Gdk.RGBA()30 bg = Gdk.RGBA()31 fg.parse('#ffffff')32 bg.parse('#1c1f22')33 self.set_color_foreground(fg)34 self.set_color_background(bg)35 36 # Create child37 self.create_child()38 39 def create_child(self):40 try:41 # Use async from version 0.4842 self.spawn_async(43 Vte.PtyFlags.DEFAULT, #pty flags44 environ['HOME'], #working directory45 ["/bin/bash"], #argmument vector46 [], #list with environment variables47 GLib.SpawnFlags.DO_NOT_REAP_CHILD, #spawn flags48 None, #child_setup function49 None, #child_setup data (gpointer)50 -1, #timeout51 self._cancellable, #cancellable52 None, #callback53 None #callback data54 )55 except:56 # TODO: self._cancellable errors out: Cancellable initialisation not supported57 self.spawn_sync(58 Vte.PtyFlags.DEFAULT, #pty flags59 environ['HOME'], #working directory60 ["/bin/bash"], #argmument vector61 [], #list with environment variables62 GLib.SpawnFlags.DO_NOT_REAP_CHILD, #spawn flags63 None, #child_setup function64 None, #child_setup data (gpointer)65 None #cancellable66 )67 68 def feed(self, command, wait_until_done=False, disable_scrolling=True, pause_logging=False):69 if self._cmd_is_running:70 return71 self._cancellable.reset()72 self.grab_focus()73 self.pause_logging = pause_logging74 command += '\n'75 self.feed_child(command.encode())76 def sleep(seconds=0.1):77 time.sleep(seconds)78 # Update the parent window79 while Gtk.events_pending():80 Gtk.main_iteration()81 # Unfortunately, there is no built-in way to notify the parent82 # that a command has finished or to wait for the command 83 # until it is finished.84 if wait_until_done:85 self._cmd_is_running = True86 # This won't work if the user scrolls up.87 # So, disable scrolling while running the command88 parent_is_sensitive = False89 try:90 if disable_scrolling:91 parent_is_sensitive = self.get_parent().get_sensitive()92 self.get_parent().set_sensitive(False)93 except:94 pass95 # First, wait until the last character is not a prompt sign96 while self.get_text(None, None)[0].strip()[-1:] in '$#':97 sleep()98 # Finally, the command is executing - wait until the last99 # character is a prompt sign100 while self.get_text(None, None)[0].strip()[-1:] not in '$#':101 sleep()102 # Make the terminal scrollable again if it was at the start103 if parent_is_sensitive: self.get_parent().set_sensitive(True)104 # Command is done105 self._cmd_is_running = False106 107 # Reset pause on logging108 self.pause_logging = False109 110 def cancel(self):111 self._cancellable.cancel()112 113 def get_last_line(self):114 text = self.get_text(None, None)[0].strip()115 text = text.split('\n')116 ii = len(text) - 1117 while text[ii] == '':118 ii = ii - 1119 text = text[ii]120 return text121 122 def get_vte_version(self):123 # Return tuple of vte version124 return Vte.get_major_version(), Vte.get_minor_version(), Vte.get_micro_version()125 126 def on_contents_changed(self, terminal):127 # Log the content of the terminal128 if self.log_file and not self.pause_logging:129 column, row = self.get_cursor_position()130 if self._last_row != row:131 text = self.get_text_range(self._last_row, 0, row, -1)[0]132 text = text.strip()133 self._last_row = row134 with open(self.log_file, 'a') as f:135 f.write(text + '\n')136 137 def on_key_press(self, widget, event):138 # Handle Ctrl-Shift-C and Ctrl-Shift-V139 if self.enable_copy_paste:140 ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)141 shift = (event.state & Gdk.ModifierType.SHIFT_MASK)142 if ctrl and shift:143 keyval = Gdk.keyval_to_upper(event.keyval)144 if keyval == Gdk.KEY_C and self.get_has_selection():145 self.copy_clipboard()146 return True147 elif keyval == Gdk.KEY_V:148 self.paste_clipboard()149 return True150 151 def on_child_exited(self, terminal, status):152 # Create a new child if the user ended the current one153 # with Ctrl-D or typing exit....
compatibility.py
Source:compatibility.py
1#!/usr/bin/python2.72# -*- coding: utf-8 -*-3'''4Faraday Penetration Test IDE5Copyright (C) 2016 Infobyte LLC (http://www.infobytesec.com/)6See the file 'doc/LICENSE' for the license information7This module is intended to function as a compatibility layer to support both8GObject Instrospection 3.12, 3.16 and 3.20 (Ubuntu 14.04, Brew on Mac OS and9Arch, respectively) and VTE API 2.90 and 2.91 (Ubuntu 14.04 has 2.90, last one10is 2.91)11'''12import gi13gi_version = gi.__version__14gi.require_version('Gtk', '3.0')15try:16 gi.require_version('Vte', '2.91')17 vte_version = '2.91'18except ValueError:19 gi.require_version('Vte', '2.90')20 vte_version = '2.90'21from gi.repository import Vte, Gtk22class CompatibleVteTerminal(Vte.Terminal):23 """A simple VTE terminal modified to be compatible with both 2.9024 and 2.91 API"""25 def __init__(self):26 Vte.Terminal.__init__(self)27 def spawn_sync(self, pty_flags, working_directory, argument_vector,28 env_variables, glib_spawn_flags, child_setup,29 child_setup_data, cancellable=None):30 """Returns the corresponden version os 'spawn_sync' method31 according to the Vte version the user has"""32 if vte_version == '2.91':33 return Vte.Terminal.spawn_sync(self, pty_flags, working_directory,34 argument_vector, env_variables,35 glib_spawn_flags, child_setup,36 child_setup_data, cancellable)37 elif vte_version == '2.90':38 return Vte.Terminal.fork_command_full(self, pty_flags,39 working_directory,40 argument_vector, env_variables,41 glib_spawn_flags, child_setup,42 child_setup_data, cancellable)43class CompatibleScrolledWindow(Gtk.ScrolledWindow):44 """A simple Gtk.ScrolledWindow, replacing set_overlay_scrolling for None45 if Gobject Instrospection is too old."""46 def __init__(self, *args, **kwargs):47 Gtk.ScrolledWindow.__init__(self, *args, **kwargs)48 @staticmethod49 def new(hadjustment, vadjustment):50 return Gtk.ScrolledWindow.new(hadjustment, vadjustment)51 def set_overlay_scrolling(self, boolean):52 """Return the set_overlay_scrolling method, if it can."""53 if gi_version == '3.12.0' or gi_version == '3.14.0':54 return None55 else:...
combination_list_of_list.py
Source:combination_list_of_list.py
1from itertools import product2import re3ef combo_1(main_parent_band,child_band):4 main_parent_list = main_parent_band.split("\n")5 child_band_list = child_band.split("\n")6 main_parent_setup = []7 8 for i in range(0,len(main_parent_list)):9 main_parent_loop = re.findall(r'\d+\.*\d*',str(main_parent_list[i]))10 main_parent_setup.append(main_parent_loop)11 superset =list(product(*main_parent_setup))12 #print("superset:",superset)13 child_setup = []14 for j in range(0,len(child_band_list)):15 child_loop = re.findall(r'\d+\.*\d*',str(child_band_list[j]))16 child_setup.append(child_loop)17 18 child = list(product(*child_setup))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!