def __init__(self, title=None): #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - super(Screen, self).__init__() self.hout = w32con.GetStdHandle(w32con.STD_OUTPUT_HANDLE) self.hin = w32con.GetStdHandle(w32con.STD_INPUT_HANDLE) self.oldHINMode = self.hin.GetConsoleMode() self.oldHOUTMode = self.hout.GetConsoleMode() #print "0x%0x" % self.oldHINMode, "0x%0x" % self.oldHOUTMode self.SetMode(0xf8, 0x3) self.info = self.hout.GetConsoleScreenBufferInfo() self.screen = self.info["Window"] ## location of current cursor self.x = 0 self.y = 0 self.updateXY() self.clearInput() self.ignSet = set([16, 17, 18, 19, 112, 46, 33, 34, 20, 91]) if title is not None: self.SetTitle(title)
def _ClearScreen(self): """Clears the terminal/console screen.""" if self._have_ansi_support: # ANSI escape sequence to clear screen. self._output_writer.Write('\033[2J') # ANSI escape sequence to move cursor to top left. self._output_writer.Write('\033[H') elif win32console: # This version of Windows cmd.exe does not support ANSI escape codes, thus # instead we fill the console screen buffer with spaces. The downside of # this approach is an annoying flicker. top_left_coordinate = win32console.PyCOORDType(0, 0) screen_buffer = win32console.GetStdHandle( win32api.STD_OUTPUT_HANDLE) screen_buffer_information = screen_buffer.GetConsoleScreenBufferInfo( ) screen_buffer_attributes = screen_buffer_information['Attributes'] screen_buffer_size = screen_buffer_information['Size'] console_size = screen_buffer_size.X * screen_buffer_size.Y screen_buffer.FillConsoleOutputCharacter(' ', console_size, top_left_coordinate) screen_buffer.FillConsoleOutputAttribute(screen_buffer_attributes, console_size, top_left_coordinate) screen_buffer.SetConsoleCursorPosition(top_left_coordinate)
def terminate_in_thread(self, command, process): """ Terminate the subprocess """ logger.debug("Terminating wrapper") if command == "train": timeout = self.config.tk_vars["traintimeout"].get() logger.debug("Sending Exit Signal") print("Sending Exit Signal", flush=True) now = time() if os.name == "nt": logger.debug("Sending carriage return to process") con_in = win32console.GetStdHandle( # pylint:disable=c-extension-no-member win32console.STD_INPUT_HANDLE) # pylint:disable=c-extension-no-member keypress = self.generate_windows_keypress("\n") con_in.WriteConsoleInput([keypress]) else: logger.debug("Sending SIGINT to process") process.send_signal(signal.SIGINT) while True: timeelapsed = time() - now if process.poll() is not None: break if timeelapsed > timeout: logger.error("Timeout reached sending Exit Signal") self.terminate_all_children() else: self.terminate_all_children() return True
def __init__(self): import win32console colors = dict( BLACK=[], BLUE=['BLUE'], CYAN=['GREEN', 'BLUE'], GREEN=['GREEN'], MAGENTA=['RED', 'BLUE'], RED=['RED'], WHITE=['RED', 'GREEN', 'BLUE'], YELLOW=['RED', 'GREEN'], ) self._foreground_map = color_map = { '' : 0 } for color_name, color_components in colors.iteritems(): if color_components: value = getattr(win32console, 'FOREGROUND_INTENSITY') else: value = 0 for component in color_components: value |= getattr(win32console, 'FOREGROUND_' + component) color_map[color_name] = value #Some of the calls below could raise exceptions, in which case we should #fallback to another approach! self._output_handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) self._reset = self._output_handle.GetConsoleScreenBufferInfo()['Attributes'] self._console = win32console.PyConsoleScreenBufferType(self._output_handle)
def initConsole(self, consout=None, window_size_x=80, window_size_y=25, buffer_size_x=80, buffer_size_y=16000): if not consout: consout = self.getConsoleOut() self.consin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) rect = win32console.PySMALL_RECTType(0, 0, window_size_x - 1, window_size_y - 1) consout.SetConsoleWindowInfo(True, rect) size = win32console.PyCOORDType(buffer_size_x, buffer_size_y) consout.SetConsoleScreenBufferSize(size) pos = win32console.PyCOORDType(0, 0) # Use NUL as fill char because it displays as whitespace # (if we interact() with the child) consout.FillConsoleOutputCharacter(screenbufferfillchar, size.X * size.Y, pos) consinfo = consout.GetConsoleScreenBufferInfo() self.__consSize = consinfo['Size'] logger.info('self.__consSize: ' + str(self.__consSize)) self.startCursorPos = consinfo['CursorPosition']
def __init__(self, verbose=True): self._prefix = '' self._skip_bottom_line = False # If true, messages are printed one line above the cursor self._verbose = verbose self._print_lock = threading.Lock() if platform.system() == 'Windows': self._stdout_buf = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
def output_colorized(self, message): """colorize a message on windows""" #pylint: disable=import-error import win32console #pylint: enable=import-error fn = getattr(self.stream, 'fileno', None) if fn is not None: #pylint: disable=not-callable fd = fn() #pylint: enable=not-callable if fd in (1, 2): # stdout or stderr c = win32console.GetStdHandle(-10 - fd) parts = self.ansiEscapes.split(message) while parts: text = parts.pop(0) if text: self.stream.write(text) if parts: params = parts.pop(0) if c is not None: params = [int(p) for p in params.split(';')] color = 0 for p in params: if 40 <= p <= 47: color |= self.winColorMap[p - 40] << 4 elif 30 <= p <= 37: color |= self.winColorMap[p - 30] elif p == 1: color |= 0x08 # Foreground intensity on elif p == 0: # Reset to default color color = 0x07 else: pass # Unknown color command - ignore it c.SetConsoleTextAttribute(color)
def set_wait_for_input(): global _wait_for_input if is_wine(): #don't wait for input when running under wine #(which usually does not popup a new shell window) _wait_for_input = False return try: handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) #handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) console_info = handle.GetConsoleScreenBufferInfo() cpos = console_info["CursorPosition"] #wait for input if this is a brand new console: _wait_for_input = cpos.X == 0 and cpos.Y == 0 except: e = sys.exc_info()[1] code = -1 try: code = e.winerror except: pass if code == errno.ENXIO: #ignore "no device" errors silently #(ie: happens if you redirect the command to a file) #we could also re-use the code above from "not_a_console()" pass else: print("error accessing console %s: %s" % (errno.errorcode.get(e.errno, e.errno), e))
def disable_quick_edit(): """Disable the 'quick-edit' misfeature of Windows' cmd.exe, in which a single click on the console puts it in 'select' mode indefinitely, causing writes to stdout from the program to block, freezing the program. The program remains paused like this even if the window is no longer focused, until the user sends a keypress to the console. This breaks so many things and is easy to do without realising it. This function disables the feature, and and adds an atexit() hook to set it back back to its initial configuration when Python exits. """ if os.name == 'nt' and all([ a is not None and a.isatty() and _get_fileno(a) >= 0 for a in (sys.stdin, sys.stdout, sys.stderr) ]): import win32console import atexit import pywintypes ENABLE_QUICK_EDIT = 0x0040 ENABLE_EXTENDED_FLAGS = 0x0080 console = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) try: orig_mode = console.GetConsoleMode() except pywintypes.error: # Probably there is no console after all. # Don't know why, but don't worry about it: return if (orig_mode & ENABLE_EXTENDED_FLAGS) and not (orig_mode & ENABLE_QUICK_EDIT): # Already disabled, nothing for us to do. return new_mode = (orig_mode | ENABLE_EXTENDED_FLAGS) & ~ENABLE_QUICK_EDIT console.SetConsoleMode(new_mode) atexit.register(console.SetConsoleMode, orig_mode)
def init_console(self): """Sets up connection to console.""" try: win32console.AttachConsole(-1) # pythonw.exe from console atexit.register(lambda: ConsoleWriter.realwrite("\n")) except Exception: pass # Okay if fails: can be python.exe from console try: handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) handle.WriteConsole("\n") ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.WriteConsole except Exception: # Fails if GUI program: make new console try: win32console.FreeConsole() except Exception: pass try: win32console.AllocConsole() handle = open("CONOUT$", "w") argv = [util.longpath(sys.argv[0])] + sys.argv[1:] handle.write(" ".join(argv) + "\n\n") handle.flush() ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.write sys.stdin = open("CONIN$", "r") atexit.register(self.on_exe_exit) except Exception: try: win32console.FreeConsole() except Exception: pass ConsoleWriter.realwrite = self.stream.write ConsoleWriter.is_loaded = True
def _ClearScreen(self): """Clears the terminal/console screen.""" if not win32console: # ANSI escape sequence to clear screen. self._output_writer.Write(b'\033[2J') # ANSI escape sequence to move cursor to top left. self._output_writer.Write(b'\033[H') else: # Windows cmd.exe does not support ANSI escape codes, thus instead we # fill the console screen buffer with spaces. top_left_coordinate = win32console.PyCOORDType(0, 0) screen_buffer = win32console.GetStdHandle( win32api.STD_OUTPUT_HANDLE) screen_buffer_information = screen_buffer.GetConsoleScreenBufferInfo( ) screen_buffer_attributes = screen_buffer_information[u'Attributes'] screen_buffer_size = screen_buffer_information[u'Size'] console_size = screen_buffer_size.X * screen_buffer_size.Y screen_buffer.FillConsoleOutputCharacter(u' ', console_size, top_left_coordinate) screen_buffer.FillConsoleOutputAttribute(screen_buffer_attributes, console_size, top_left_coordinate) screen_buffer.SetConsoleCursorPosition(top_left_coordinate)
def __init__(self): self.inbuf = None if not self.is_attached(): raise ConsoleError("process not attached to a console") self.inbuf = win32console.PyConsoleScreenBufferType( win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)) self.outbuf = win32console.PyConsoleScreenBufferType( win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)) self.clear_events() self.cursor = Cursor(self.outbuf) self.screen = Screen(self.outbuf) self._orig_mode = self.inbuf.GetConsoleMode() self._orig_attrs = self.cursor.get_attributes() self.inbuf.SetConsoleMode(self._orig_mode & ~win32console.ENABLE_LINE_INPUT & ~win32console.ENABLE_ECHO_INPUT & ~win32console.ENABLE_PROCESSED_INPUT)
def __init__(self, parent_pid, lst_cmd_line): try: _ConsoleProcessBase.__init__(self, parent_pid) self.parent_pid = parent_pid self._start_parent_monitor() self.cmd_line = ' '.join(lst_cmd_line) self.echo = eval(os.environ.get('pyconsole_echo', 'True')) self.child_handle = None self.child_pid = None self.paused = False self.x_max = 0 self.y_max = 0 self.y_buffer_max = 0 self.y_last = 0 self.y_adjust = 0 self.y_current = 0 self.last_event_time = 0 self._initialize() self._initialize_events() win32console.FreeConsole() # alloc 2000 lines ? win32console.AllocConsole() self.con_stdout = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) self.con_stdin = win32console.GetStdHandle( win32console.STD_INPUT_HANDLE) win32console.SetConsoleTitle('console process pid:%s ppid:%s' % ( os.getpid(), parent_pid, )) # size = win32console.PyCOORDType (X=1000, Y=30) # self.con_stdout.SetConsoleScreenBufferSize (size) dct_info = self.con_stdout.GetConsoleScreenBufferInfo() self.y_buffer_max = dct_info['Size'].Y - 1 self.con_window = win32console.GetConsoleWindow().handle self.set_console_event_hook() self._start_paused_monitor() self._child_create() self._start_remote_input() self.message_pump() except: logging.exception('fatal error')
def print_ok(string): if sys.platform.startswith('win'): import win32console font_color = win32console.FOREGROUND_INTENSITY | win32console.FOREGROUND_GREEN console = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) old_color = console.GetConsoleScreenBufferInfo()['Attributes'] console.SetConsoleTextAttribute(font_color) print(string) console.SetConsoleTextAttribute(old_color) else: print(string)
def quick_edit_mode(turn_on=None): """ Enable/Disable windows console Quick Edit Mode """ screen_buffer = win32console.GetStdHandle(-10) orig_mode = screen_buffer.GetConsoleMode() is_on = (orig_mode & ENABLE_QUICK_EDIT_MODE) if is_on != turn_on and turn_on is not None: if turn_on: new_mode = orig_mode | ENABLE_QUICK_EDIT_MODE else: new_mode = orig_mode & ~ENABLE_QUICK_EDIT_MODE screen_buffer.SetConsoleMode(new_mode | ENABLE_EXTENDED_FLAGS) return is_on if turn_on is None else turn_on
def write(self, text): """ Prints text to console window. GUI application will need to attach to the calling console, or launch a new console if not available. """ global window if not window and win32console: if not ConsoleWriter.is_loaded and not ConsoleWriter.handle: try: win32console.AttachConsole(-1) # pythonw.exe from console atexit.register(lambda: ConsoleWriter.realwrite("\n")) except Exception: pass # Okay if fails: can be python.exe from console try: handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) handle.WriteConsole("\n" + text) ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.WriteConsole except Exception: # Fails if GUI program: make new console try: win32console.FreeConsole() except Exception: pass try: win32console.AllocConsole() handle = open("CONOUT$", "w") argv = [util.longpath(sys.argv[0])] + sys.argv[1:] handle.write(" ".join(argv) + "\n\n" + text) handle.flush() ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.write sys.stdin = open("CONIN$", "r") exitfunc = lambda s: (handle.write(s), handle.flush(), raw_input()) atexit.register(exitfunc, "\nPress ENTER to exit.") except Exception: try: win32console.FreeConsole() except Exception: pass ConsoleWriter.realwrite = self.stream.write ConsoleWriter.is_loaded = True else: try: self.realwrite(text) self.flush() except Exception: self.stream.write(text) else: self.stream.write(text)
def __call__(self, prompt, prefill=''): import win32console _stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) keys = [] for c in str(prefill): evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT) evt.Char = c evt.RepeatCount = 1 evt.KeyDown = True keys.append(evt) _stdin.WriteConsoleInput(keys) return input(prompt)
def termwidth(): try: # Query stderr to avoid problems with redirections screenbuf = win32console.GetStdHandle(win32console.STD_ERROR_HANDLE) if screenbuf is None: return 79 try: window = screenbuf.GetConsoleScreenBufferInfo()['Window'] width = window.Right - window.Left return width finally: screenbuf.Detach() except pywintypes.error: return 79
def do_init(): if not REDIRECT_OUTPUT: if sys.version_info[0] < 3: #don't know why this breaks with Python 3 yet... fix_unicode_out() #figure out if we want to wait for input at the end: global _wait_for_input try: import win32console, win32con #@UnresolvedImport handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) #handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) console_info = handle.GetConsoleScreenBufferInfo() cpos = console_info["CursorPosition"] #wait for input if this is a brand new console: _wait_for_input = cpos.X == 0 and cpos.Y == 0 except: e = sys.exc_info()[1] code = -1 try: code = e.winerror except: pass if code == errno.ENXIO: #ignore "no device" errors silently #(ie: happens if you redirect the command to a file) #we could also re-use the code above from "not_a_console()" pass else: print("error accessing console %s: %s" % (errno.errorcode.get(e.errno, e.errno), e)) if _wait_for_input: #don't wait for input when running under wine #(which usually does not popup a new shell window) try: import win32api #@UnresolvedImport hKey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, r"Software\\Wine") if hKey is not None: _wait_for_input = False except: #no wine key, assume not present and wait for input pass return from xpra.platform import get_prgname LOG_FILENAME = get_prgname() + ".log" from paths import _get_data_dir d = _get_data_dir() log_file = os.path.join(d, LOG_FILENAME) sys.stdout = open(log_file, "a") sys.stderr = sys.stdout
def InitConsoleScreenBuffer(): self._output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) if self._output_handle is None: self._console_screen_buffer = None else: try: self._reset = self._output_handle.GetConsoleScreenBufferInfo( )['Attributes'] except Exception: # There is no valid console, such as when running from inside Eclipse. self._console_screen_buffer = None else: self._console_screen_buffer = win32console.PyConsoleScreenBufferType( self._output_handle)
def loading(lenght=20, speed=0.2): j = 0 for i in range(lenght): output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) info = output_handle.GetConsoleScreenBufferInfo() pos = info["CursorPosition"] a = "/-\\|" output_handle.WriteConsoleOutputCharacter(a[j], pos) sys.stdout.write(".") time.sleep(speed) sys.stdout.flush() j = j + 1 if j == 4: j = 0 print("\n")
def do_init(): if not REDIRECT_OUTPUT: fix_unicode_out() #figure out if we want to wait for input at the end: global _wait_for_input try: import win32console, win32con #@UnresolvedImport handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) #handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) console_info = handle.GetConsoleScreenBufferInfo() cpos = console_info["CursorPosition"] #wait for input if this is a brand new console: _wait_for_input = cpos.X == 0 and cpos.Y == 0 except Exception, e: print("error accessing console: %s" % e) return
def supported(cls, stream=sys.stdout): try: import win32console screenBuffer = win32console.GetStdHandle( win32console.STD_OUT_HANDLE) except ImportError: return False import pywintypes try: screenBuffer.SetConsoleTextAttribute( win32console.FOREGROUND_RED | win32console.FOREGROUND_GREEN | win32console.FOREGROUND_BLUE) except pywintypes.error: return False else: return True
def main(): """main function for AI console application""" # handle = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) try: if handle.GetConsoleMode(): pipeOut("MESSAGE Gomoku AI should not be started directly. Please install gomoku manager (http://sourceforge.net/projects/piskvork). Then enter path to this exe file in players settings.") except pywintypes.error: pass # global event1, event2 event1 = win32event.CreateEvent(None, 0, 0, None) win32process.beginthreadex(None, 0, threadLoop, (), 0) event2 = win32event.CreateEvent(None, 1, 1, None) while True: cmd = get_line() do_command(cmd)
def __init__(self, std_handle_type, old_stdout): threading.Thread.__init__(self) # so that if the main thread exit, our thread will also exit self.setDaemon(True) self.stdout_pipe = os.pipe() self.file_descriptor = self.stdout_pipe[0] self.std_handle_type = std_handle_type self.old_stdout = old_stdout # use for internal purpose self.screen_buffer = win32console.GetStdHandle(self.std_handle_type) # do not open the file in text mode, otherwise it will try to decode # with the encoding, but the unicode sometimes included something # do not in the encoding scale, that will case a convertion error: # 'ascii' codec can't encode character u'\xbb' in position ... self.stdout = io.open(self.file_descriptor, mode='rb') self.stdin = None
def __init__(self, stream): import win32console as win red, green, blue, bold = (win.FOREGROUND_RED, win.FOREGROUND_GREEN, win.FOREGROUND_BLUE, win.FOREGROUND_INTENSITY) self.stream = stream self.screenBuffer = win.GetStdHandle(win.STD_OUT_HANDLE) self._colors = { 'normal': red | green | blue, 'red': red | bold, 'green': green | bold, 'blue': blue | bold, 'yellow': red | green | bold, 'magenta': red | blue | bold, 'cyan': green | blue | bold, 'white': red | green | blue | bold }
def main(): """main function for AI console application""" handle = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) try: if handle.GetConsoleMode(): send_msg( "MESSAGE Gomoku AI should not be started directly. Please install gomoku manager (http://sourceforge.net/projects/piskvork). Then enter path to this exe file in players settings." ) except pywintypes.error: pass file_name = os.path.join(utils.LOG_PATH, 'temp') pipe = open(file_name, 'w+') process = subprocess.Popen( ['python', os.path.join(utils.ROOT_PATH, 'gomocup.py')], stderr=pipe, stdout=pipe) logger = Logger('manager', handlers=['File']) logger.info('start background process') socket = SocketServer(*SOCKET_INIT_PARA) socket.bind_addr(utils.HOST, utils.PORT) logger.info('socket bind success') # a = process.communicate() try: # now keep talking with the client while True: cmd = recv_msg() logger.info(cmd) if cmd == 'STOP': socket.send_msg('END') break else: socket.send_msg(cmd) msg = socket.recv_msg() if msg != 'None': send_msg(msg) logger.info(msg) finally: pipe.close() socket.close() process.kill() os.remove(file_name)
def RunAs(self): #username = "******" #domain = "." #password ="******" cmd = "uninstall.exe" free_console = True try: win32console.AllocConsole() except win32console.error as exc: if exc.winerror != 5: raise ## only free console if one was created successfully free_console = False stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) #p = subprocess.Popen(["runas",r"/user:{}\{}".format(domain,username),cmd],stdout=subprocess.PIPE) subprocess.Popen("runas /savecred /user:Administrator %s" % cmd, shell=True) '''
def main(): handle = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) try: if handle.GetConsoleMode(): pipe_out( "MESSAGE Gomoku AI should not be started directly. Please install gomoku manager (http://sourceforge.net/projects/piskvork). Then enter path to this exe file in players settings." ) except pywintypes.error: pass t_recv = threading.Thread(target=listen, daemon=True) t_recv.start() sock_send = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_send.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_send.connect((ADDR, SEND_PORT)) # print('Sending to %s %s' % (ADDR, SEND_PORT)) while True: line = get_line() sock_send.sendall(line.encode('utf-8')) if line.lower().startswith('end'): sys.exit(0)
def __init__(self, size): super().__init__(size) self.draw.pixel = self.draw._db_pixel stdcon = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) self.active_screen = 0 self.screens = [ win32console.CreateConsoleScreenBuffer( DesiredAccess=win32con.GENERIC_READ | win32con.GENERIC_WRITE, ShareMode=0, SecurityAttributes=None, Flags=1), win32console.CreateConsoleScreenBuffer( DesiredAccess=win32con.GENERIC_READ | win32con.GENERIC_WRITE, ShareMode=0, SecurityAttributes=None, Flags=1) ] self.screens[self.active_screen].SetConsoleActiveScreenBuffer() self.cursor_size, _ = stdcon.GetConsoleCursorInfo() self.backbuffer = self.screens[1]