我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用sys.__stdin__()。
def win_getpass(prompt='Password: ', stream=None): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) import msvcrt for c in prompt: msvcrt.putch(c) pw = "" while 1: c = msvcrt.getch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putch('\r') msvcrt.putch('\n') return pw
def get_terminal_size(fallback=(80, 24)): """ Return tuple containing columns and rows of controlling terminal, trying harder than shutil.get_terminal_size to find a tty before returning fallback. Theoretically, stdout, stderr, and stdin could all be different ttys that could cause us to get the wrong measurements (instead of using the fallback) but the much more common case is that IO is piped. """ for stream in [sys.__stdout__, sys.__stderr__, sys.__stdin__]: try: # Make WINSIZE call to terminal data = fcntl.ioctl(stream.fileno(), TIOCGWINSZ, b"\x00\x00\00\x00") except (IOError, OSError): pass else: # Unpack two shorts from ioctl call lines, columns = struct.unpack("hh", data) break else: columns, lines = fallback return columns, lines
def become_daemon(self, root_dir='/'): if os.fork() != 0: # launch child and ... os._exit(0) # kill off parent os.setsid() os.chdir(root_dir) os.umask(0) if os.fork() != 0: # fork again so we are not a session leader os._exit(0) sys.stdin.close() sys.__stdin__ = sys.stdin sys.stdout.close() sys.stdout = sys.__stdout__ = _NullDevice() sys.stderr.close() sys.stderr = sys.__stderr__ = _NullDevice() for fd in range(1024): try: os.close(fd) except OSError: pass
def onecmd(self, line): cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if line == 'EOF': # reset stdin for raw_input sys.stdin = sys.__stdin__ Framework._script = 0 Framework._load = 0 return 0 if cmd is None: return self.default(line) self.lastcmd = line if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg) # make help menu more attractive
def win_getpass(prompt='Password: ', stream=None): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) import msvcrt for c in prompt: msvcrt.putwch(c) pw = "" while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def fix_windows_stdout_stderr(): """ Processes can't write to stdout/stderr on frozen windows apps because they do not exist here if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy see https://github.com/jopohl/urh/issues/370 """ if hasattr(sys, "frozen") and sys.platform == "win32": try: sys.stdout.write("\n") sys.stdout.flush() except: class DummyStream(object): def __init__(self): pass def write(self, data): pass def read(self, data): pass def flush(self): pass def close(self): pass sys.stdout, sys.stderr, sys.stdin = DummyStream(), DummyStream(), DummyStream() sys.__stdout__, sys.__stderr__, sys.__stdin__ = DummyStream(), DummyStream(), DummyStream()
def run(fun, args, input, output): sys.stdin = input sys.stdout = output fun(args) sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__
def tearDown(self): super(HookChefTest, self).tearDown() sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__
def workaroundForGUI(): """ redirect I/O when in GUI ref: http://stackoverflow.com/questions/2883205/how-can-i-freeze-a-dual-mode-gui-and-console-application-using-cx-freeze ref: https://mail.gnome.org/archives/commits-list/2012-November/msg04489.html ref: http://stackoverflow.com/questions/23505835/cx-freeze-ignores-custom-variables-module """ try: sys.stdout.write("\n") sys.stdout.flush() except Exception as e: class GuiLogger: logfile = os.path.realpath(os.path.realpath(sys.argv[0])) logfile = os.path.splitext(logfile)[0] + '.log' logObj = open(logfile, "w") def __init__(self): self.logObj = GuiLogger.logObj def write(self, data): self.logObj.write(data) def flush(self): self.logObj.flush() def close(self): self.flush() def read(self, data): pass sys.stdout = sys.stderr = sys.stdin = sys.__stdout__ = sys.__stdin__ = sys.__stderr__ = GuiLogger() # ref: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
def test_check_interactive_good(self): # kind of unnecessary because test relies on low level function self.assertTrue(ui._check_interactive(sys.__stdin__))
def main(): from idlelib import PyShell PathBrowser(PyShell.flist) if sys.stdin is sys.__stdin__: mainloop()
def main(): try: file = __file__ except NameError: file = sys.argv[0] if sys.argv[1:]: file = sys.argv[1] else: file = sys.argv[0] dir, file = os.path.split(file) name = os.path.splitext(file)[0] ClassBrowser(PyShell.flist, name, [dir]) if sys.stdin is sys.__stdin__: mainloop()
def onecmd(self, line): cmd, arg, line = self.parseline(line) if not line or line.startswith('#'): return self.emptyline() if line == 'EOF': # reset stdin for raw_input sys.stdin = sys.__stdin__ Framework._script = 0 Framework._load = 0 self.printer.notify('Resource file successfully loaded') return 0 if cmd is None: return self.default(line) self.lastcmd = line if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg) # ================================================================================================================== # COMPLETE METHODS # ==================================================================================================================
def main(): if getattr(sys, "frozen", False) and sys.platform in ['win32','cygwin','win64']: # and now redirect all default streams to DummyStream: sys.stdout = DummyStream() sys.stderr = DummyStream() sys.stdin = DummyStream() sys.__stdout__ = DummyStream() sys.__stderr__ = DummyStream() sys.__stdin__ = DummyStream() # Get application path app_path = getAppPath() if sys.platform == 'darwin' and hasattr(sys, 'frozen'): resources_path = os.path.normpath(os.path.abspath(os.path.join(app_path, "..", "Resources"))) else: resources_path = os.path.normpath(os.path.abspath(os.path.join(app_path, "Resources"))) # Application setup app = QSingleApplication(sys.argv) app.setOrganizationName('Sumokoin') app.setOrganizationDomain('www.sumokoin.org') app.setApplicationName(APP_NAME) app.setProperty("AppPath", app_path) app.setProperty("ResPath", resources_path) if sys.platform == 'darwin': app.setAttribute(QtCore.Qt.AA_DontShowIconsInMenus) if not _check_file_integrity(app): QMessageBox.critical(None, "Application Fatal Error", """<b>File integrity check failed!</b> <br><br>This could be a result of unknown (maybe, malicious) action<br> to wallet code files.""") app.quit() else: hub = Hub(app=app) ui = MainWebUI(app=app, hub=hub, debug=False) hub.setUI(ui) app.singleStart(ui) sys.exit(app.exec_())
def disable(): sys.stdin.flush() sys.stdout.flush() sys.stderr.flush() sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ # PY3 # def enable(*, stdin=Ellipsis, stdout=Ellipsis, stderr=Ellipsis):
def _import(name, filename=None): """ Run the given callable in a 'sandboxed' environment. Currently, this includes saving and restoring the contents of sys and __builtins__; and suppressing stdin, stdout, and stderr. """ # Note that we just do a shallow copy of sys. In particular, # any changes made to sys.modules will be kept. But we do # explicitly store sys.path. old_sys = sys.__dict__.copy() old_sys_path = sys.path[:] old_builtins = __builtin__.__dict__.copy() # Add the current directory to sys.path, in case they're trying to # import a module by name that resides in the current directory. # But add it to the end -- otherwise, the explicit directory added # in get_value_from_filename might get overwritten sys.path.append('') # Suppress input and output. (These get restored when we restore # sys to old_sys). sys.stdin = sys.stdout = sys.stderr = _dev_null sys.__stdin__ = sys.__stdout__ = sys.__stderr__ = _dev_null # Remove any command-line arguments sys.argv = ['(imported)'] try: try: if filename is None: return __import__(name) else: # For importing scripts: return imp.load_source(name, filename) except KeyboardInterrupt: raise except: exc_typ, exc_val, exc_tb = sys.exc_info() if exc_val is None: estr = '%s' % (exc_typ,) else: estr = '%s: %s' % (exc_typ.__name__, exc_val) if exc_tb.tb_next is not None: estr += ' (line %d)' % (exc_tb.tb_next.tb_lineno,) raise ImportError(estr) finally: # Restore the important values that we saved. __builtin__.__dict__.clear() __builtin__.__dict__.update(old_builtins) sys.__dict__.clear() sys.__dict__.update(old_sys) sys.path = old_sys_path
def step(context, args): from StringIO import StringIO import sys context.stdin = StringIO() context.stdout = StringIO() context.stderr = StringIO() try: sys.stdin = context.stdin sys.stdout = context.stdout sys.stderr = context.stderr if [s for s in context.scenario.steps if 'should be prompted' in s.name]: # Fake this out for scenarios that expect a prompt sys.stdin.write("yes\n") else: # Scenarios that don't expect a prompt but get one will fail sys.stdin.write("no\n") sys.stdin.seek(0) if 'cli_config' in context and context.cli_config: standard_cli(args=args.split(), config=context.cli_config) else: # Set env vars for username/password so that we don't need # to pollute the features files with them. os.environ['CHROMA_USERNAME'] = 'admin' os.environ['CHROMA_PASSWORD'] = 'lustre' standard_cli(args.split()) except SystemExit, e: context.stdout.seek(0) context.stderr.seek(0) forced = any([a in ['--force', '-f'] for a in args.split()]) if e.code != 0 and not context.cli_failure_expected: fail("code: %d stdout: %s stderr: %s" % (e.code, context.stdout.readlines(), context.stderr.readlines())) elif e.code == 0 and context.cli_failure_expected and not forced: fail("Failure expected but didn't happen!\nstdout: %s, stderr: %s" % (context.stdout.readlines(), context.stderr.readlines())) except Exception, e: context.stdout.seek(0) context.stderr.seek(0) from traceback import format_exc fail("%s\nstdout:\n%s\nstderr:\n%s" % (format_exc(), "".join(context.stdout.readlines()), "".join(context.stderr.readlines()))) sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__
def cbreak(self): """ Allow each keystroke to be read immediately after it is pressed. This is a context manager for :func:`tty.setcbreak`. This context manager activates 'rare' mode, the opposite of 'cooked' mode: On entry, :func:`tty.setcbreak` mode is activated disabling line-buffering of keyboard input and turning off automatic echo of input as output. .. note:: You must explicitly print any user input you would like displayed. If you provide any kind of editing, you must handle backspace and other line-editing control functions in this mode as well! **Normally**, characters received from the keyboard cannot be read by Python until the *Return* key is pressed. Also known as *cooked* or *canonical input* mode, it allows the tty driver to provide line-editing before shuttling the input to your program and is the (implicit) default terminal mode set by most unix shells before executing programs. Technically, this context manager sets the :mod:`termios` attributes of the terminal attached to :obj:`sys.__stdin__`. .. note:: :func:`tty.setcbreak` sets ``VMIN = 1`` and ``VTIME = 0``, see http://www.unixwiz.net/techtips/termios-vmin-vtime.html """ if HAS_TTY and self._keyboard_fd is not None: # Save current terminal mode: save_mode = termios.tcgetattr(self._keyboard_fd) save_line_buffered = self._line_buffered tty.setcbreak(self._keyboard_fd, termios.TCSANOW) try: self._line_buffered = False yield finally: # Restore prior mode: termios.tcsetattr(self._keyboard_fd, termios.TCSAFLUSH, save_mode) self._line_buffered = save_line_buffered else: yield