Python sys.__stdin__() Examples

The following are code examples for showing how to use sys.__stdin__(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: style50   Author: cs50   File: style50.py    (license) View Source Project 7 votes vote down vote up
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 
Example 2
Project: hostapd-mana   Author: adde88   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 3
Project: SameKeyProxy   Author: xzhou   File: daemonizer.py    (license) View Source Project 6 votes vote down vote up
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 
Example 4
Project: pentestly   Author: praetorian-inc   File: framework.py    (license) View Source Project 6 votes vote down vote up
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 
Example 5
Project: MKFQ   Author: maojingios   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 6
Project: zippy   Author: securesystemslab   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: oil   Author: oilshell   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 8
Project: sslstrip-hsts-openwrt   Author: adde88   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 9
Project: recon-ng   Author: Hehe-Zhc   File: framework.py    (license) View Source Project 6 votes vote down vote up
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 
Example 10
Project: xxNet   Author: drzorm   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 11
Project: pefile.pypy   Author: cloudtracer   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 12
Project: ouroboros   Author: pybee   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 13
Project: ndk-python   Author: gittor   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 14
Project: empyrion-python-api   Author: huhlig   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 15
Project: recon-ng   Author: captainhooligan   File: framework.py    (license) View Source Project 6 votes vote down vote up
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 
Example 16
Project: kbe_server   Author: xiaohaoppy   File: getpass.py    (license) View Source Project 6 votes vote down vote up
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 
Example 17
Project: urh   Author: jopohl   File: main.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 18
Project: code   Author: ActiveState   File: recipe-474094.py    (MIT License) View Source Project 5 votes vote down vote up
def run(fun, args, input, output):
    sys.stdin  = input
    sys.stdout = output
    fun(args)
    sys.stdin  = sys.__stdin__
    sys.stdout = sys.__stdout__ 
Example 19
Project: heat-agents   Author: openstack   File: test_hook_chef.py    (license) View Source Project 5 votes vote down vote up
def tearDown(self):
        super(HookChefTest, self).tearDown()
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__ 
Example 20
Project: spe2fits   Author: jerryjiahaha   File: spe2fitsGUI.py    (license) View Source Project 5 votes vote down vote up
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 
Example 21
Project: Intranet-Penetration   Author: yuxiaokui   File: getpass.py    (license) View Source Project 5 votes vote down vote up
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 
Example 22
Project: calmjs   Author: calmjs   File: test_ui.py    (license) View Source Project 5 votes vote down vote up
def test_check_interactive_good(self):
        # kind of unnecessary because test relies on low level function
        self.assertTrue(ui._check_interactive(sys.__stdin__)) 
Example 23
Project: zippy   Author: securesystemslab   File: PathBrowser.py    (license) View Source Project 5 votes vote down vote up
def main():
    from idlelib import PyShell
    PathBrowser(PyShell.flist)
    if sys.stdin is sys.__stdin__:
        mainloop() 
Example 24
Project: zippy   Author: securesystemslab   File: ClassBrowser.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 25
Project: python2-tracer   Author: extremecoders-re   File: getpass.py    (license) View Source Project 5 votes vote down vote up
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 
Example 26
Project: needle   Author: mwrlabs   File: framework.py    (license) View Source Project 5 votes vote down vote up
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
    # ================================================================================================================== 
Example 27
Project: ndk-python   Author: gittor   File: PathBrowser.py    (license) View Source Project 5 votes vote down vote up
def main():
    from idlelib import PyShell
    PathBrowser(PyShell.flist)
    if sys.stdin is sys.__stdin__:
        mainloop() 
Example 28
Project: ndk-python   Author: gittor   File: ClassBrowser.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 29
Project: SumoGUIWallet   Author: sumoprojects   File: main.py    (license) View Source Project 5 votes vote down vote up
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_()) 
Example 30
Project: Docker-XX-Net   Author: kuanghy   File: getpass.py    (license) View Source Project 5 votes vote down vote up
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 
Example 31
Project: blender   Author: gastrodia   File: streams.py    (license) View Source Project 5 votes vote down vote up
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): 
Example 32
Project: python-driver   Author: bblfsh   File: issue_server101.py    (GNU General Public License v3.0) View Source Project 4 votes vote down vote up
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 
Example 33
Project: kinect-2-libras   Author: inessadl   File: getpass.py    (Apache License 2.0) View Source Project 4 votes vote down vote up
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 
Example 34
Project: intel-manager-for-lustre   Author: intel-hpdd   File: standard_cli.py    (license) View Source Project 4 votes vote down vote up
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__ 
Example 35
Project: HPCinstall   Author: NCAR   File: terminal.py    (license) View Source Project 4 votes vote down vote up
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