Python threading.Thread 模块,__init__() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用threading.Thread.__init__()。
def __init__(self, phrases, tables_of_from, columns_of_values_of_where, count_keywords, sum_keywords,
average_keywords, max_keywords, min_keywords, greater_keywords, less_keywords, between_keywords,
negation_keywords, junction_keywords, disjunction_keywords, like_keywords, distinct_keywords,
database_dico, database_object):
Thread.__init__(self)
self.where_objects = []
self.phrases = phrases
self.tables_of_from = tables_of_from
self.columns_of_values_of_where = columns_of_values_of_where
self.count_keywords = count_keywords
self.sum_keywords = sum_keywords
self.average_keywords = average_keywords
self.max_keywords = max_keywords
self.min_keywords = min_keywords
self.greater_keywords = greater_keywords
self.less_keywords = less_keywords
self.between_keywords = between_keywords
self.negation_keywords = negation_keywords
self.junction_keywords = junction_keywords
self.disjunction_keywords = disjunction_keywords
self.like_keywords = like_keywords
self.distinct_keywords = distinct_keywords
self.database_dico = database_dico
self.database_object = database_object
def __init__(self, cluster, timeout,
schema_event_refresh_window,
topology_event_refresh_window,
status_event_refresh_window,
schema_meta_enabled=True,
token_meta_enabled=True):
# use a weak reference to allow the Cluster instance to be GC'ed (and
# shutdown) since implementing __del__ disables the cycle detector
self._cluster = weakref.proxy(cluster)
self._connection = None
self._timeout = timeout
self._schema_event_refresh_window = schema_event_refresh_window
self._topology_event_refresh_window = topology_event_refresh_window
self._status_event_refresh_window = status_event_refresh_window
self._schema_meta_enabled = schema_meta_enabled
self._token_meta_enabled = token_meta_enabled
self._lock = RLock()
self._schema_agreement_lock = Lock()
self._reconnection_handler = None
self._reconnection_lock = RLock()
self._event_schedule_times = {}
def __init__(self, world, viewport):
self.world = world
self.viewport = viewport
x_min, y_min, x_max, y_max = self.world
X_min, Y_min, X_max, Y_max = self.viewport
f_x = float(X_max-X_min) / float(x_max-x_min)
f_y = float(Y_max-Y_min) / float(y_max-y_min)
self.f = min(f_x,f_y)
x_c = 0.5 * (x_min + x_max)
y_c = 0.5 * (y_min + y_max)
X_c = 0.5 * (X_min + X_max)
Y_c = 0.5 * (Y_min + Y_max)
self.c_1 = X_c - self.f * x_c
self.c_2 = Y_c - self.f * y_c
## Maps a single point from world coordinates to viewport (screen) coordinates.
#
# @param x, y given point.
# @return a new point in screen coordinates.
#
def __init__(self, callback, msg_types=NFCT_T_NEW|NFCT_T_DESTROY):
Thread.__init__(self)
self.h = nfct.nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS)
if self.h == 0:
libc.perror("nfct_open")
raise Exception("nfct_open failed!")
buf = create_string_buffer(1024)
self._stop = False
def event_callback_closure(type, ct, data):
nfct.nfct_snprintf(buf, 1024, ct, type, NFCT_O_XML, NFCT_OF_TIME)
callback(buf.value)
if self._stop:
return NFCT_CB_STOP
return NFCT_CB_CONTINUE
self.cb = NFCT_CALLBACK(event_callback_closure)
nfct.nfct_callback_register(self.h, msg_types, self.cb, 0)
def __init__(self, app, db):
Thread.__init__(self)
GObject.GObject.__init__(self)
self.db = db
self.counter_max = 30
self.counter = self.counter_max
self.account_id = app[0]
self.account_name = app[1]
self.secret_code = Database.fetch_secret_code(app[2])
if self.secret_code:
self.code = Code(self.secret_code)
else:
self.code_generated = False
logging.error("Could not read the secret code,"
"the keyring keys were reset manually")
self.logo = app[3]
self.start()
def __init__(self, parent, main_window):
self.parent = parent
Thread.__init__(self)
GObject.GObject.__init__(self)
self.nom = "applications-db-reader"
self.builder = Gtk.Builder.new_from_resource("/org/gnome/Authenticator/applications.ui")
self.builder.connect_signals({
"on_close" : self.close_window,
"on_key_press": self.on_key_press,
"on_apply" : self.select_application
})
self.window = self.builder.get_object("ApplicationsWindow")
self.window.set_transient_for(main_window)
self.listbox = self.builder.get_object("ApplicationsList")
self.generate_search_bar()
self.stack = self.builder.get_object("ApplicationsStack")
self.stack.set_visible_child(self.stack.get_child_by_name("loadingstack"))
self.builder.get_object("ApplicationListScrolled").add_with_viewport(self.listbox)
self.db = []
self.start()
def __init__(self):
global AGENT_HOST
# AMQP CONFIG
endpoints = [
WampEndpoint(WampFrontend, AGENT_HOST),
]
Thread.__init__(self)
transport = oslo_messaging.get_transport(CONF)
target = oslo_messaging.Target(topic=AGENT_HOST + '.s4t_invoke_wamp',
server='server1')
access_policy = dispatcher.DefaultRPCAccessPolicy
self.server = oslo_messaging.get_rpc_server(
transport, target,
endpoints, executor='threading',
access_policy=access_policy)
def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions", "MenuActions", "EPGSelectActions"], {
"cancel": self.cancel,
"red": self.cancel,
"green" : self.save
}, -1)
self['info'] = Label(_("Settings:"))
self['key_red'] = Label(_("Cancel"))
self['key_green'] = Label(_("Ok"))
self['key_yellow'] = Label("")
self['key_blue'] = Label("")
self.list = []
self.createConfigList()
ConfigListScreen.__init__(self, self.list)
self.fileScanner = BackgroundCoverScanner.instance
def __trace__(self, state, event, payload=None):
"""
Used to record enough information that a trace can be
reported to the user when the call the trace function.
"""
if self.ltrace.state_n_0 is None:
self.ltrace.state_n_0 = "__init__"
if payload is None:
payload = None
ts = time.time()
dt = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S.%f')
self.trace_buffer.append(Trace(state_n_0=self.ltrace.state_n_0,
state_n_1=state,
event=event,
payload=deepcopy(payload),
chart=self.name))
if self.live_trace:
print(self.trace_formatter(dt, self.ltrace.state_n_0, state, event, payload, self.name))
self.ltrace.state_n_0 = state
def __init__(self, q, **kwargs):
Thread.__init__(self)
self._running = True
self.payload = None
self.period = PostEvent.POSTED_DEFAULT_DELAY
self.times = 1
self.q = q
self.deferred = False
if 'times' in kwargs:
self.times = kwargs['times']
if 'period' in kwargs:
self.period = kwargs['period']
if 'event' in kwargs:
self.event = kwargs['event']
if 'payload' in kwargs:
self.payload = kwargs['payload']
if 'deferred' in kwargs:
self.deferred = kwargs['deferred']
def __init__(self, opt, shared=None):
# Check for setup_data
if not hasattr(self, 'setup_data'):
raise RuntimeError('Must implement setup_data or subclass a class' +
' which implements it (e.g. FbDialogTeacher)' +
' in order to use this class.')
super().__init__(opt, shared)
self.startTime = time.time()
self.datatype = opt['datatype']
self.training = self.datatype.startswith('train')
self.stream = 'stream' in self.datatype.split(':')
if not self.use_batch_act:
# first initialize any shared objects
data_class = StreamDialogData if self.stream else DialogData
kwargs = {'cycle': self.training} if self.stream else {}
if shared and shared.get('data'):
self.data = data_class(opt, shared=shared['data'], **kwargs)
else:
self.data = data_class(opt, data_loader=self.setup_data,
cands=self.label_candidates(), **kwargs)
self.reset()
def __init__(self,
monitor_queue,
active_queue,
timeout,
threadpool,
*args,
**kwargs):
Thread.__init__(self, *args, **kwargs)
self._threadpool = threadpool
# Instance Variables
self.monitor_queue = monitor_queue
self.active_queue = active_queue
self.timeout = timeout
self.log = logging.getLogger('Rocket.Monitor')
self.log.addHandler(NullHandler())
self.connections = set()
self.active = False
def __init__(self,request, client_address, server):
self.server = server
self.protocol_version = 'HTTP/1.1'
self.challengeMessage = None
self.target = None
self.client = None
self.machineAccount = None
self.machineHashes = None
self.domainIp = None
global ATTACKED_HOSTS
if self.server.target in ATTACKED_HOSTS and self.server.one_shot:
logging.info(
"HTTPD: Received connection from %s, skipping %s, already attacked" % (
client_address[0], self.server.target))
return
if self.server.target is not None:
logging.info(
"HTTPD: Received connection from %s, attacking target %s" % (client_address[0], self.server.target))
else:
logging.info(
"HTTPD: Received connection from %s, attacking target %s" % (client_address[0], client_address[0]))
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
def __init__(self, username='', password='', domain='', hashes=None, aesKey=None,
doKerberos=None, kdcHost=None, mode=None, share=None, port=445):
self.__username = username
self.__password = password
self.__port = port
self.__serviceName = 'BTOBTO'
self.__domain = domain
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = aesKey
self.__doKerberos = doKerberos
self.__kdcHost = kdcHost
self.__share = share
self.__mode = mode
self.shell = None
if hashes is not None:
self.__lmhash, self.__nthash = hashes.split(':')
def __init__(self, target, targetIp=None, username='', password='', domain='', hashes=None, command='',
copyFile=None, writeTGT=None, kdcHost=None):
self.__username = username
self.__password = password
self.__domain = domain
self.__rid = 0
self.__lmhash = ''
self.__nthash = ''
self.__target = target
self.__targetIp = targetIp
self.__kdcHost = None
self.__copyFile = copyFile
self.__command = command
self.__writeTGT = writeTGT
self.__domainSid = ''
self.__forestSid = None
self.__domainControllers = list()
self.__kdcHost = kdcHost
if hashes is not None:
self.__lmhash, self.__nthash = hashes.split(':')
self.__lmhash = unhexlify(self.__lmhash)
self.__nthash = unhexlify(self.__nthash)
def __init__(self, columns_of_select, tables_of_from, phrase, count_keywords, sum_keywords, average_keywords,
max_keywords, min_keywords, distinct_keywords, database_dico, database_object):
Thread.__init__(self)
self.select_objects = []
self.columns_of_select = columns_of_select
self.tables_of_from = tables_of_from
self.phrase = phrase
self.count_keywords = count_keywords
self.sum_keywords = sum_keywords
self.average_keywords = average_keywords
self.max_keywords = max_keywords
self.min_keywords = min_keywords
self.distinct_keywords = distinct_keywords
self.database_dico = database_dico
self.database_object = database_object
def __init__(self, tables_of_from, columns_of_select, columns_of_where, database_object):
Thread.__init__(self)
self.queries = []
self.tables_of_from = tables_of_from
self.columns_of_select = columns_of_select
self.columns_of_where = columns_of_where
self.database_object = database_object
self.database_dico = self.database_object.get_tables_into_dictionary()
def __init__(self, phrases, tables_of_from, database_dico, database_object):
Thread.__init__(self)
self.group_by_objects = []
self.phrases = phrases
self.tables_of_from = tables_of_from
self.database_dico = database_dico
self.database_object = database_object
def __init__(self, phrases, tables_of_from, asc_keywords, desc_keywords, database_dico, database_object):
Thread.__init__(self)
self.order_by_objects = []
self.phrases = phrases
self.tables_of_from = tables_of_from
self.asc_keywords = asc_keywords
self.desc_keywords = desc_keywords
self.database_dico = database_dico
self.database_object = database_object
def __init__(self, sender):
Thread.__init__(self)
self.sender = sender
last_sent_time = get_timestamp()
print('Connecting to chat server...')
irc.connect((server, 6667))
irc.send('USER ' + nick + ' ' + nick + ' ' + nick + ' :Hack the Planet!\n')
irc.send('NICK ' + nick + '\n')
irc.send('JOIN ' + channel + '\n')
time.sleep(connect_delay)
self.sender.start()
pass
def __init__ (self, command, use_term = True, callback = None):
Thread.__init__(self)
self.command = command
self.use_term = use_term
self.callback = callback
def __init__ (self, prog, sec):
Thread.__init__(self)
self.prog = prog
self.sec = sec
def __init__(self, parent = None):
"""
Default Constructor. It can receive a top window as parent.
"""
QMainWindow.__init__(self, parent)
self.setupUi(self)
def __init__ (self, command, use_term = True, callback = None):
Thread.__init__(self)
self.command = command
self.use_term = use_term
self.callback = callback
def __init__ (self, prog, sec):
Thread.__init__(self)
self.prog = prog
self.sec = sec
def __init__(self, host, port, tor):
Thread.__init__(self)
self.host = host
self.port = port
self.socks = socks.socksocket()
self.tor = tor
self.running = True
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def __init__(self, signature_lib_path):
self.set_logger()
self._signature_lib_path = signature_lib_path
self._work_queue = Queue()
self._auth_queue = PriorityQueue()
self._workers = []
self._api_endpoint = 'https://pgorelease.nianticlabs.com/plfe/rpc'
self.log.info('%s v%s - %s', __title__, __version__, __copyright__)
self.log.info('%s',__patchedBy__)
def __init__(self, signature_lib_path, work_queue, auth_queue):
Thread.__init__(self)
self.log = logging.getLogger(__name__)
self._running = True
self._work_queue = work_queue
self._auth_queue = auth_queue
self._session = requests.session()
self._session.headers.update({'User-Agent': 'Niantic App'})
self._session.verify = True
self.rpc_api = RpcApi(None)
self.rpc_api._session = self._session
self.rpc_api.activate_signature(signature_lib_path)
def __init__(self, scan_config):
Thread.__init__(self)
self.daemon = True
self.name = 'search_thread'
self.api = PGoApi(config['SIGNATURE_LIB_PATH'])
self.scan_config = scan_config
def __init__(self, version, flags, stream, opcode, body_offset, end_pos):
self.version = version
self.flags = flags
self.stream = stream
self.opcode = opcode
self.body_offset = body_offset
self.end_pos = end_pos
def __init__(self, message, host=None):
Exception.__init__(self, message)
self.host = host
def __init__(self, host, startup_version):
msg = "Unsupported protocol version on %s: %d" % (host, startup_version)
super(ProtocolVersionUnsupported, self).__init__(msg, host)
self.startup_version = startup_version
def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
ssl_options=None, sockopts=None, compression=True,
cql_version=None, protocol_version=ProtocolVersion.MAX_SUPPORTED, is_control_connection=False,
user_type_map=None, connect_timeout=None, allow_beta_protocol_version=False):
self.host = host
self.port = port
self.authenticator = authenticator
self.ssl_options = ssl_options.copy() if ssl_options else None
self.sockopts = sockopts
self.compression = compression
self.cql_version = cql_version
self.protocol_version = protocol_version
self.is_control_connection = is_control_connection
self.user_type_map = user_type_map
self.connect_timeout = connect_timeout
self.allow_beta_protocol_version = allow_beta_protocol_version
self._push_watchers = defaultdict(set)
self._requests = {}
self._iobuf = io.BytesIO()
if ssl_options:
self._check_hostname = bool(self.ssl_options.pop('check_hostname', False))
if self._check_hostname:
if not getattr(ssl, 'match_hostname', None):
raise RuntimeError("ssl_options specify 'check_hostname', but ssl.match_hostname is not provided. "
"Patch or upgrade Python to use this option.")
if protocol_version >= 3:
self.max_request_id = min(self.max_in_flight - 1, (2 ** 15) - 1)
# Don't fill the deque with 2**15 items right away. Start with some and add
# more if needed.
initial_size = min(300, self.max_in_flight)
self.request_ids = deque(range(initial_size))
self.highest_request_id = initial_size - 1
else:
self.max_request_id = min(self.max_in_flight, (2 ** 7) - 1)
self.request_ids = deque(range(self.max_request_id + 1))
self.highest_request_id = self.max_request_id
self.lock = RLock()
self.connected_event = Event()
def __init__(self, connection, num_responses, fail_on_error):
self.connection = connection
self.pending = num_responses
self.fail_on_error = fail_on_error
self.error = None
self.responses = [None] * num_responses
self.event = Event()
def __init__(self, interval_sec, get_connection_holders, timeout):
Thread.__init__(self, name="Connection heartbeat")
self._interval = interval_sec
self._timeout = timeout
self._get_connection_holders = get_connection_holders
self._shutdown_event = Event()
self.daemon = True
self.start()
def __init__(self, timeout, callback):
self.end = time.time() + timeout
self.callback = callback
def __init__(self):
self._queue = []
self._new_timers = []
def __init__(self, message, errors):
Exception.__init__(self, message, errors)
self.errors = errors
def __init__(self, load_balancing_policy=None, retry_policy=None,
consistency_level=ConsistencyLevel.LOCAL_ONE, serial_consistency_level=None,
request_timeout=10.0, row_factory=named_tuple_factory, speculative_execution_policy=None):
self.load_balancing_policy = load_balancing_policy or default_lbp_factory()
self.retry_policy = retry_policy or RetryPolicy()
self.consistency_level = consistency_level
self.serial_consistency_level = serial_consistency_level
self.request_timeout = request_timeout
self.row_factory = row_factory
self.speculative_execution_policy = speculative_execution_policy or NoSpeculativeExecutionPolicy()
def __init__(self, cluster, hosts, keyspace=None):
self.cluster = cluster
self.hosts = hosts
self.keyspace = keyspace
self._lock = RLock()
self._pools = {}
self._profile_manager = cluster.profile_manager
self._metrics = cluster.metrics
self._request_init_callbacks = []
self._protocol_version = self.cluster.protocol_version
self.encoder = Encoder()
# create connection pools in parallel
self._initial_connect_futures = set()
for host in hosts:
future = self.add_or_renew_pool(host, is_host_addition=False)
if future:
self._initial_connect_futures.add(future)
futures = wait_futures(self._initial_connect_futures, return_when=FIRST_COMPLETED)
while futures.not_done and not any(f.result() for f in futures.done):
futures = wait_futures(futures.not_done, return_when=FIRST_COMPLETED)
if not any(f.result() for f in self._initial_connect_futures):
msg = "Unable to connect to any servers"
if self.keyspace:
msg += " using keyspace '%s'" % self.keyspace
raise NoHostAvailable(msg, [h.address for h in hosts])
def __init__(self, control_connection, *args, **kwargs):
_ReconnectionHandler.__init__(self, *args, **kwargs)
self.control_connection = weakref.proxy(control_connection)
def __init__(self, executor):
self._queue = Queue.PriorityQueue()
self._scheduled_tasks = set()
self._count = count()
self._executor = executor
Thread.__init__(self, name="Task Scheduler")
self.daemon = True
self.start()
def __init__(self, response_future, initial_response):
self.response_future = response_future
self.column_names = response_future._col_names
self.column_types = response_future._col_types
self._set_current_rows(initial_response)
self._page_iter = None
self._list_mode = False
def __init__(self, thread_num, session, query, values, num_queries, protocol_version, profile):
Thread.__init__(self)
self.thread_num = thread_num
self.session = session
self.query = query
self.values = values
self.num_queries = num_queries
self.protocol_version = protocol_version
self.profiler = Profile() if profile else None
def __init__(self):
Thread.__init__(self)
self.done = []
self.stop = []