#!/usr/bin/env python
# Licensed under the MIT license
# A simple SQLite shell that uses the built-in Python adapter.
import codecs
import io
import os
import sys
import sqlite3
import time
import warnings
try: FileNotFoundError
except NameError: FileNotFoundError = OSError
if str != bytes: buffer = bytes
if str != bytes: unicode = str
try: import msvcrt
except ImportError: msvcrt = None
CP_UTF8 = 65001
pythonapi = None
if msvcrt:
import ctypes
(BOOL, DWORD, HANDLE, UINT) = (ctypes.c_long, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_uint)
GetConsoleCP = ctypes.WINFUNCTYPE(UINT)(('GetConsoleCP', ctypes.windll.kernel32))
SetConsoleCP = ctypes.WINFUNCTYPE(BOOL, UINT)(('SetConsoleCP', ctypes.windll.kernel32))
GetConsoleOutputCP = ctypes.WINFUNCTYPE(UINT)(('GetConsoleOutputCP', ctypes.windll.kernel32))
SetConsoleOutputCP = ctypes.WINFUNCTYPE(BOOL, UINT)(('SetConsoleOutputCP', ctypes.windll.kernel32))
GetConsoleMode = ctypes.WINFUNCTYPE(BOOL, HANDLE, ctypes.POINTER(DWORD), use_last_error=True)(('GetConsoleMode', ctypes.windll.kernel32))
GetNumberOfConsoleInputEvents = ctypes.WINFUNCTYPE(BOOL, HANDLE, ctypes.POINTER(DWORD), use_last_error=True)(('GetNumberOfConsoleInputEvents', ctypes.windll.kernel32))
ReadConsoleW = ctypes.WINFUNCTYPE(BOOL, HANDLE, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD), ctypes.c_void_p, use_last_error=True)(('ReadConsoleW', ctypes.windll.kernel32))
WriteConsoleW = ctypes.WINFUNCTYPE(BOOL, HANDLE, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD), ctypes.c_void_p, use_last_error=True)(('WriteConsoleW', ctypes.windll.kernel32))
class Py_buffer(ctypes.Structure): _fields_ = [('buf', ctypes.c_void_p), ('obj', ctypes.py_object), ('len', ctypes.c_ssize_t), ('itemsize', ctypes.c_ssize_t), ('readonly', ctypes.c_int), ('ndim', ctypes.c_int), ('format', ctypes.c_char_p), ('shape', ctypes.POINTER(ctypes.c_ssize_t)), ('strides', ctypes.POINTER(ctypes.c_ssize_t)), ('suboffsets', ctypes.POINTER(ctypes.c_ssize_t))] + ([('smalltable', ctypes.c_ssize_t * 2)] if sys.version_info[0] <= 2 else []) + [('internal', ctypes.c_void_p)]
try: from ctypes import pythonapi
except ImportError: pass
if pythonapi:
def getbuffer(b, writable):
arr = Py_buffer()
pythonapi.PyObject_GetBuffer(ctypes.py_object(b), ctypes.byref(arr), ctypes.c_int(writable))
try: buf = (ctypes.c_ubyte * arr.len).from_address(arr.buf)
finally: pythonapi.PyBuffer_Release(ctypes.byref(arr))
return buf
ENCODING = 'utf-8'
if sys.version_info[0] < 3:
class NotASurrogateError(Exception): pass
def surrogateescape_handler(exc):
# Source: https://github.com/PythonCharmers/python-future/blob/aef57391c0cd58bf840dff5e2bc2c8c0f5b0a1b4/src/future/utils/surrogateescape.py
mystring = exc.object[exc.start:exc.end]
try:
if isinstance(exc, UnicodeDecodeError):
decoded = []
for ch in mystring:
if isinstance(ch, int):
code = ch
else:
code = ord(ch)
if 0x80 <= code <= 0xFF:
decoded.append(unichr(0xDC00 + code))
elif code <= 0x7F:
decoded.append(unichr(code))
else:
raise NotASurrogateError()
decoded = str().join(decoded)
elif isinstance(exc, UnicodeEncodeError):
decoded = []
for ch in mystring:
code = ord(ch)
if not 0xD800 <= code <= 0xDCFF:
raise NotASurrogateError()
if 0xDC00 <= code <= 0xDC7F:
decoded.append(unichr(code - 0xDC00))
elif code <= 0xDCFF:
decoded.append(unichr(code - 0xDC00))
else:
raise NotASurrogateError()
decoded = str().join(decoded)
else:
raise exc
except NotASurrogateError:
raise exc
return (decoded, exc.end)
codecs.register_error('surrogateescape', surrogateescape_handler)
def exception_encode(ex, codec):
if str == bytes:
reduced = ex.__reduce__()
ex = reduced[0](*tuple(map(lambda arg: codec.decode(arg)[0] if isinstance(arg, bytes) else arg, reduced[1])))
return ex
def sql_commands(read_line):
delims = ['"', "'", ';', '--']
counter = 0
in_string = None
j = i = 0
prev_line = None
line = None
concat = []
while True:
if line is None:
while True: # process preprocessor directives
counter += 1
not_in_the_middle_of_any_input = not in_string and i == j and all(map(lambda chunk_: len(chunk_) == 0, concat))
line = read_line(counter - 1, not_in_the_middle_of_any_input, prev_line)
empty_string = line[:0] if line is not None else line
prev_line = line
if not line:
break
if not_in_the_middle_of_any_input and line.startswith("."):
yield line
line = None
else:
break
if not line:
break
j = i = 0
if j < len(line):
(j, delim) = min(map(lambda pair: pair if pair[0] >= 0 else (len(line), pair[1]), map(lambda d: (line.find(d, j), d), in_string or delims if in_string != '--' else "\n")))
if i < j: concat.append(line[i:j]); i = j
if not in_string:
if j < len(line):
j += len(delim)
if delim == ';':
i = j
concat.append(line[j : j + len(delim)]) # ensure delimeter is the same type as the string (it may not be due to implicit conversion)
# Eat up any further spaces until a newline
while j < len(line):
delim = line[j:j+1]
if not delim.isspace(): break
j += 1
if delim == "\n": break
if i < j: concat.append(line[i:j]); i = j
yield empty_string.join(concat)
del concat[:]
else:
in_string = delim
else:
if j < len(line):
ch = line[j:j+1]
assert ch == in_string or in_string == '--'
j += 1
i = j
concat.append(ch)
in_string = None
else:
if i < j: concat.append(line[i:j]); i = j
line = None
class WindowsConsoleIOMixin(object):
# Ctrl+C handling with ReadFile() is messed up on Windows starting on Windows 8... here's some background reading:
# https://stackoverflow.com/a/43260436
# https://github.com/microsoft/terminal/issues/334
# We use ReadConsole when we can, so it doesn't affect us, but it's good info to know regardless.
def __init__(self, fd):
assert isatty(fd), "file descriptor must refer to a console (note that on Windows, NUL satisfies isatty(), but is not a console)"
self.fd = fd
self.handle = msvcrt.get_osfhandle(fd)
def fileno(self): return self.fd
def isatty(self): return isatty(self.fd)
def seekable(self): return False
def readable(self): return GetNumberOfConsoleInputEvents(self.handle, ctypes.byref(DWORD(0))) != 0
def writable(self): n = DWORD(0); return WriteConsoleW(self.handle, ctypes.c_void_p(), n, ctypes.byref(n), ctypes.c_void_p()) != 0
def readwcharsinto(self, buf, n):
nr = DWORD(n)
old_error = ctypes.get_last_error()
ctypes.set_last_error(0)
success = ReadConsoleW(self.handle, buf, nr, ctypes.byref(nr), ctypes.c_void_p())
error = ctypes.get_last_error()
ctypes.set_last_error(old_error)
if not success: raise ctypes.WinError(error)
ERROR_OPERATION_ABORTED = 995
if nr.value == 0 and error == ERROR_OPERATION_ABORTED:
# Apparently this can trigger pending KeyboardInterrupts?
time.sleep(1.0 / (1 << 64))
raise KeyboardInterrupt() # If Python doesn't raise it, we can
return nr.value
def writewchars(self, buf, n):
nw = DWORD(n)
if not WriteConsoleW(self.handle, buf, nw, ctypes.byref(nw), ctypes.c_void_p()):
raise ctypes.WinError()
return nw.value
class WindowsConsoleRawIO(WindowsConsoleIOMixin, io.RawIOBase):
def readinto(self, b):
wordsize = ctypes.sizeof(ctypes.c_wchar)
return self.readwcharsinto(getbuffer(b, True), len(b) // wordsize) * wordsize
def write(self, b):
wordsize = ctypes.sizeof(ctypes.c_wchar)
return self.writewchars(getbuffer(b, False), len(b) // wordsize) * wordsize
class WindowsConsoleTextIO(WindowsConsoleIOMixin, io.TextIOBase):
buf = None
buffered = unicode()
translate = True
def getbuf(self, ncodeunits):
buf = self.buf
if buf is None or len(buf) < ncodeunits:
self.buf = buf = ctypes.create_unicode_buffer(ncodeunits)
return buf
@staticmethod # Don't let classes override this... they can over
没有合适的资源?快使用搜索试试~ 我知道了~
released_hw_hw10_hw10.zip
共8个文件
py:5个
ok:2个
sql:1个
需积分: 5 0 下载量 88 浏览量
2022-11-27
23:23:09
上传
评论
收藏 777KB ZIP 举报
温馨提示
released_hw_hw10_hw10.zip
资源推荐
资源详情
资源评论
收起资源包目录
released_hw_hw10_hw10.zip (8个子文件)
hw10
hw10.ok 331B
ok 2.59MB
hw10.sql 2KB
sqlite_shell.py 32KB
tests
size_of_dogs.py 566B
sentences.py 589B
__init__.py 0B
by_parent_height.py 567B
共 8 条
- 1
资源评论
qq_74597377
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功