Python sys.stdout() Examples

The following are code examples for showing how to use sys.stdout(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 9 votes vote down vote up
def print_csv(self, value, header):
        """CSV print."""
        if header is not None:
            writer = csv.DictWriter(self.stdout, header)
            writer.writeheader()
            for row in value:
                writer.writerow(
                    {k: self.format_csv_value(v) for k, v in row.items()}
                )
        elif isinstance(list(value.items())[0][1], dict):
            for key, data in sorted_items(value):
                self.println(self.format_csv_value(key))
                self.print_csv(data, None)
                self.println(self.format_csv_value(''))
        else:
            writer = csv.writer(self.stdout)
            for key, data in sorted_items(value):
                writer.writerow((key, self.format_csv_value(data))) 
Example 2
Project: fs_image   Author: facebookincubator   File: layer_mount_config.py    MIT License 6 votes vote down vote up
def main(stdin, stdout, layer_target):
    mount_config = json.load(stdin)

    for key in ('build_source', 'is_directory'):
        if key in mount_config:
            raise RuntimeError(
                f'`{key}` must not be set in `mount_config = {mount_config}`'
            )

    mount_config['is_directory'] = True
    mount_config['build_source'] = {
        # Don't attempt to target-tag this because this would complicate
        # MountItem, which would have to contain `Subvol` and know how to
        # serialize it (P106589820).  This is much messier than the current
        # approach of explicit target & layer lookups in `_BuildSource`.
        'source': layer_target,
        # The compiler knows how to resolve the above target to a layer path.
        # For now, we don't support mounting a subdirectory of a layer because
        # that might make packaging more complicated, but it could be done.
        'type': 'layer',
    }

    json.dump(mount_config, stdout) 
Example 3
Project: ubittool   Author: carlosperate   File: test_gui.py    MIT License 6 votes vote down vote up
def test_window_console(capsys):
    """Test the std our and err go to the console widget."""
    std_out_content = "This is content in the std out\n"
    std_err_content = "And this goes to the std err\n"

    with capsys.disabled():
        app = UBitToolWindow()
        app.wait_visibility()

        sys.stdout.write(std_out_content)
        sys.stderr.write(std_err_content)
        console_widget_content = app.console.get(1.0, "end")

        app.update()
        app.destroy()

    assert std_out_content in console_widget_content
    assert std_err_content in console_widget_content 
Example 4
Project: ubittool   Author: carlosperate   File: test_gui.py    MIT License 6 votes vote down vote up
def test_quit():
    """Test that when the window is closed it deactivates the console."""
    app = UBitToolWindow()
    app.wait_visibility()

    assert sys.stdout != sys.__stdout__
    assert sys.stderr != sys.__stderr__

    app.app_quit()

    assert sys.stdout == sys.__stdout__
    assert sys.stderr == sys.__stderr__
    try:
        app.winfo_exists()
    except tkinter.TclError:
        # App destroyed, nothing left to do
        assert True, "Window was already destroyed"
    else:
        raise AssertionError("Window is not destroyed") 
Example 5
Project: pyblish-win   Author: pyblish   File: webchecker.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    checkext = CHECKEXT
    verbose = VERBOSE
    maxpage = MAXPAGE
    roundsize = ROUNDSIZE
    dumpfile = DUMPFILE
    restart = 0
    norun = 0

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print __doc__%globals()
        sys.exit(2)

    # The extra_roots variable collects extra roots. 
Example 6
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
                 indentsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
        self.fpi = fpi
        self.fpo = fpo
        self.indentsize = indentsize
        self.tabsize = tabsize
        self.lineno = 0
        self.expandtabs = expandtabs
        self._write = fpo.write
        self.kwprog = re.compile(
                r'^(?:\s|\\\n)*(?P<kw>[a-z]+)'
                r'((?:\s|\\\n)+(?P<id>[a-zA-Z_]\w*))?'
                r'[^\w]')
        self.endprog = re.compile(
                r'^(?:\s|\\\n)*#?\s*end\s+(?P<kw>[a-z]+)'
                r'(\s+(?P<id>[a-zA-Z_]\w*))?'
                r'[^\w]')
        self.wsprog = re.compile(r'^[ \t]*')
    # end def __init__ 
Example 7
Project: pyblish-win   Author: pyblish   File: mkreal.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    sys.stdout = sys.stderr
    progname = os.path.basename(sys.argv[0])
    if progname == '-c': progname = 'mkreal'
    args = sys.argv[1:]
    if not args:
        print 'usage:', progname, 'path ...'
        sys.exit(2)
    status = 0
    for name in args:
        if not os.path.islink(name):
            print progname+':', name+':', 'not a symlink'
            status = 1
        else:
            if os.path.isdir(name):
                mkrealdir(name)
            else:
                mkrealfile(name)
    sys.exit(status) 
Example 8
Project: pyblish-win   Author: pyblish   File: hotshotmain.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def run_hotshot(filename, profile, args):
    prof = hotshot.Profile(profile)
    sys.path.insert(0, os.path.dirname(filename))
    sys.argv = [filename] + args
    prof.run("execfile(%r)" % filename)
    prof.close()
    stats = hotshot.stats.load(profile)
    stats.sort_stats("time", "calls")

    # print_stats uses unadorned print statements, so the only way
    # to force output to stderr is to reassign sys.stdout temporarily
    save_stdout = sys.stdout
    sys.stdout = sys.stderr
    stats.print_stats()
    sys.stdout = save_stdout

    return 0 
Example 9
Project: pyblish-win   Author: pyblish   File: ifdef.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
    for o, a in opts:
        if o == '-D':
            defs.append(a)
        if o == '-U':
            undefs.append(a)
    if not args:
        args = ['-']
    for filename in args:
        if filename == '-':
            process(sys.stdin, sys.stdout)
        else:
            f = open(filename, 'r')
            process(f, sys.stdout)
            f.close() 
Example 10
Project: pyblish-win   Author: pyblish   File: md5sum.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def sum(*files):
    sts = 0
    if files and isinstance(files[-1], file):
        out, files = files[-1], files[:-1]
    else:
        out = sys.stdout
    if len(files) == 1 and not isinstance(files[0], str):
        files = files[0]
    for f in files:
        if isinstance(f, str):
            if f == '-':
                sts = printsumfp(sys.stdin, '<stdin>', out) or sts
            else:
                sts = printsum(f, out) or sts
        else:
            sts = sum(f, out) or sts
    return sts 
Example 11
Project: pyblish-win   Author: pyblish   File: fixcid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def fix(filename):
##  dbg('fix(%r)\n' % (filename,))
    if filename == '-':
        # Filter mode
        f = sys.stdin
        g = sys.stdout
    else:
        # File replacement mode
        try:
            f = open(filename, 'r')
        except IOError, msg:
            err(filename + ': cannot open: ' + str(msg) + '\n')
            return 1
        head, tail = os.path.split(filename)
        tempname = os.path.join(head, '@' + tail)
        g = None
    # If we find a match, we rewind the file and start over but
    # now copy everything to a temp file. 
Example 12
Project: pyblish-win   Author: pyblish   File: cmd.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, completekey='tab', stdin=None, stdout=None):
        """Instantiate a line-oriented interpreter framework.

        The optional argument 'completekey' is the readline name of a
        completion key; it defaults to the Tab key. If completekey is
        not None and the readline module is available, command completion
        is done automatically. The optional arguments stdin and stdout
        specify alternate input and output file objects; if not specified,
        sys.stdin and sys.stdout are used.

        """
        import sys
        if stdin is not None:
            self.stdin = stdin
        else:
            self.stdin = sys.stdin
        if stdout is not None:
            self.stdout = stdout
        else:
            self.stdout = sys.stdout
        self.cmdqueue = []
        self.completekey = completekey 
Example 13
Project: pyblish-win   Author: pyblish   File: pstats.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwds):
        # I can't figure out how to explictly specify a stream keyword arg
        # with *args:
        #   def __init__(self, *args, stream=sys.stdout): ...
        # so I use **kwds and sqauwk if something unexpected is passed in.
        self.stream = sys.stdout
        if "stream" in kwds:
            self.stream = kwds["stream"]
            del kwds["stream"]
        if kwds:
            keys = kwds.keys()
            keys.sort()
            extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys])
            raise ValueError, "unrecognized keyword args: %s" % extras
        if not len(args):
            arg = None
        else:
            arg = args[0]
            args = args[1:]
        self.init(arg)
        self.add(*args) 
Example 14
Project: pyblish-win   Author: pyblish   File: telnetlib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def interact(self):
        """Interaction function, emulates a very dumb telnet client."""
        if sys.platform == "win32":
            self.mt_interact()
            return
        while 1:
            rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
            if self in rfd:
                try:
                    text = self.read_eager()
                except EOFError:
                    print '*** Connection closed by remote host ***'
                    break
                if text:
                    sys.stdout.write(text)
                    sys.stdout.flush()
            if sys.stdin in rfd:
                line = sys.stdin.readline()
                if not line:
                    break
                self.write(line) 
Example 15
Project: pyblish-win   Author: pyblish   File: fileinput.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def nextfile(self):
        savestdout = self._savestdout
        self._savestdout = 0
        if savestdout:
            sys.stdout = savestdout

        output = self._output
        self._output = 0
        if output:
            output.close()

        file = self._file
        self._file = 0
        if file and not self._isstdin:
            file.close()

        backupfilename = self._backupfilename
        self._backupfilename = 0
        if backupfilename and not self._backup:
            try: os.unlink(backupfilename)
            except OSError: pass

        self._isstdin = False
        self._buffer = []
        self._bufindex = 0 
Example 16
Project: pyblish-win   Author: pyblish   File: code.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def runcode(self, code):
        """Execute a code object.

        When an exception occurs, self.showtraceback() is called to
        display a traceback.  All exceptions are caught except
        SystemExit, which is reraised.

        A note about KeyboardInterrupt: this exception may occur
        elsewhere in this code, and may not always be caught.  The
        caller should be prepared to deal with it.

        """
        try:
            exec code in self.locals
        except SystemExit:
            raise
        except:
            self.showtraceback()
        else:
            if softspace(sys.stdout, 0):
                print 
Example 17
Project: pyblish-win   Author: pyblish   File: test_core.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_run_setup_uses_current_dir(self):
        # This tests that the setup script is run with the current directory
        # as its own current directory; this was temporarily broken by a
        # previous patch when TESTFN did not use the current directory.
        sys.stdout = StringIO.StringIO()
        cwd = os.getcwd()

        # Create a directory and write the setup.py file there:
        os.mkdir(test.test_support.TESTFN)
        setup_py = os.path.join(test.test_support.TESTFN, "setup.py")
        distutils.core.run_setup(
            self.write_setup(setup_prints_cwd, path=setup_py))

        output = sys.stdout.getvalue()
        if output.endswith("\n"):
            output = output[:-1]
        self.assertEqual(cwd, output) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_core.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_debug_mode(self):
        # this covers the code called when DEBUG is set
        sys.argv = ['setup.py', '--name']
        with captured_stdout() as stdout:
            distutils.core.setup(name='bar')
        stdout.seek(0)
        self.assertEqual(stdout.read(), 'bar\n')

        distutils.core.DEBUG = True
        try:
            with captured_stdout() as stdout:
                distutils.core.setup(name='bar')
        finally:
            distutils.core.DEBUG = False
        stdout.seek(0)
        wanted = "options (after parsing config files):\n"
        self.assertEqual(stdout.readlines()[0], wanted) 
Example 19
Project: pyblish-win   Author: pyblish   File: tool.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    if len(sys.argv) == 1:
        infile = sys.stdin
        outfile = sys.stdout
    elif len(sys.argv) == 2:
        infile = open(sys.argv[1], 'rb')
        outfile = sys.stdout
    elif len(sys.argv) == 3:
        infile = open(sys.argv[1], 'rb')
        outfile = open(sys.argv[2], 'wb')
    else:
        raise SystemExit(sys.argv[0] + " [infile [outfile]]")
    with infile:
        try:
            obj = json.load(infile)
        except ValueError, e:
            raise SystemExit(e) 
Example 20
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, args, config, stdout=None):
        """Construct Command object."""
        self.args = args
        self.config = config
        if stdout is None:
            self.stdout = sys.stdout
        else:
            self.stdout = stdout
        self.odorik = odorik.Odorik(config=config) 
Example 21
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def println(self, line):
        """Print single line to output."""
        print(line, file=self.stdout) 
Example 22
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def print_json(self, value):
        """JSON print."""
        json.dump(value, self.stdout, indent=2) 
Example 23
Project: odorik   Author: nijel   File: test_main.py    GNU General Public License v3.0 5 votes vote down vote up
def test_stdout(self):
        """Configuration using params."""
        register_uris()
        output = execute(['balance'], stdout=True)
        self.assertIn('123.45', output) 
Example 24
Project: mutatest   Author: EvanKepner   File: conftest.py    MIT License 5 votes vote down vote up
def stdoutIO():
    """Stdout redirection as a context manager to evaluating code mutations."""

    @contextlib.contextmanager
    def stdoutIO(stdout=None):
        old = sys.stdout
        if stdout is None:
            stdout = StringIO()
        sys.stdout = stdout
        yield stdout
        sys.stdout = old

    return stdoutIO 
Example 25
Project: incubator-spot   Author: apache   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_logger(cls, name, level='INFO', filepath=None, fmt=None):
        '''
            Return a new logger or an existing one, if any.

        :param cls     : The class as implicit first argument.
        :param name    : Return a logger with the specified name.
        :param filepath: Path of the file, where logs will be saved. If it is not set,
                         redirects the log stream to `sys.stdout`.
        :param fmt     : A format string for the message as a whole, as well as a format
                         string for the date/time portion of the message.
                         Default: '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        :rtype         : :class:`logging.Logger`
        '''
        logger = logging.getLogger(name)
        # .............................if logger already exists, return it
        if logger.handlers: return logger

        if filepath:
            # .........................rotate log file (1 rotation per 512KB
            handler  = RotatingFileHandler(filepath, maxBytes=524288, backupCount=8)
        else:
            handler  = logging.StreamHandler(sys.stdout)

        fmt = fmt or '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        handler.setFormatter(logging.Formatter(fmt))

        try:
            logger.setLevel(getattr(logging, level.upper() if level else 'INFO'))
        except: logger.setLevel(logging.INFO)

        logger.addHandler(handler)
        return logger 
Example 26
Project: incubator-spot   Author: apache   File: utils.py    Apache License 2.0 5 votes vote down vote up
def popen(cls, cmd, cwd=None, raises=False):
        '''
            Execute the given command string in a new process. Send data to stdin and
        read data from stdout and stderr, until end-of-file is reached.

        :param cls     : The class as implicit first argument.
        :param cwd     : If it is set, then the child's current directory will be change
                         to `cwd` before it is executed.
        :param raises  : If ``True`` and stderr has data, it raises an ``OSError`` exception.
        :returns       : The output of the given command; pair of (stdout, stderr).
        :rtype         : ``tuple``
        :raises OSError: If `raises` and stderr has data.
        '''
        parser   = lambda x: [] if x == '' else [y.strip() for y in x.strip().split('\n')]
        process  = subprocess.Popen(cmd, shell=True, universal_newlines=True,
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = process.communicate()

        # .............................trim lines and remove the empty ones
        _stdout  = [x for x in parser(out) if bool(x)]
        _stderr  = [x for x in parser(err) if bool(x)]

        if _stderr and raises:
            raise OSError('\n'.join(_stderr))

        return _stdout, _stderr 
Example 27
Project: ubittool   Author: carlosperate   File: gui.py    MIT License 5 votes vote down vote up
def activate(self):
        """Configure std out/in to send to write to the console text widget."""
        sys.stdout = StdoutRedirector(self, text_color="#0D4")
        sys.stderr = StdoutRedirector(self, text_color="#D00")
        logger = logging.getLogger()
        logger.setLevel(level=logging.INFO)
        logging_handler_out = logging.StreamHandler(sys.stdout)
        logging_handler_out.setLevel(logging.INFO)
        logger.addHandler(logging_handler_out)
        logging_handler_err = logging.StreamHandler(sys.stderr)
        logging_handler_err.setLevel(logging.WARNING)
        logger.addHandler(logging_handler_err) 
Example 28
Project: ubittool   Author: carlosperate   File: gui.py    MIT License 5 votes vote down vote up
def deactivate(self):
        """Restore std out/in."""
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__ 
Example 29
Project: clikit   Author: sdispater   File: standard_output_stream.py    MIT License 5 votes vote down vote up
def __init__(self):  # type: () -> None
        super(StandardOutputStream, self).__init__(sys.stdout) 
Example 30
Project: reelay-codegen   Author: doganulus   File: PastTLLexer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, input=None, output:TextIO = sys.stdout):
        super().__init__(input, output)
        self.checkVersion("4.7.1")
        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
        self._actions = None
        self._predicates = None 
Example 31
Project: reelay-codegen   Author: doganulus   File: RegExpParser.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
        super().__init__(input, output)
        self.checkVersion("4.7.1")
        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
        self._predicates = None 
Example 32
Project: reelay-codegen   Author: doganulus   File: PastTLParser.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
        super().__init__(input, output)
        self.checkVersion("4.7.1")
        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
        self._predicates = None 
Example 33
Project: reelay-codegen   Author: doganulus   File: RegExpLexer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, input=None, output:TextIO = sys.stdout):
        super().__init__(input, output)
        self.checkVersion("4.7.1")
        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
        self._actions = None
        self._predicates = None 
Example 34
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow3.py    MIT License 5 votes vote down vote up
def send_feedback(self):
        """Print stored items to console/Alfred as JSON."""
        json.dump(self.obj, sys.stdout)
        sys.stdout.flush() 
Example 35
Project: pyblish-win   Author: pyblish   File: wcgui.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print __doc__%vars(webchecker)
        sys.exit(2) 
Example 36
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def complete_filter(input = sys.stdin, output = sys.stdout,
                    stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    pi.complete()
# end def complete_filter 
Example 37
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def reformat_filter(input = sys.stdin, output = sys.stdout,
                    stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    pi.reformat()
# end def reformat_filter 
Example 38
Project: pyblish-win   Author: pyblish   File: ftpmirror.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def usage(*args):
    sys.stdout = sys.stderr
    for msg in args: print msg
    print __doc__
    sys.exit(2) 
Example 39
Project: pyblish-win   Author: pyblish   File: objgraph.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def warndups():
    savestdout = sys.stdout
    sys.stdout = sys.stderr
    names = def2file.keys()
    names.sort()
    for name in names:
        if len(def2file[name]) > 1:
            print 'warning:', name, 'multiply defined:',
            print flat(def2file[name])
    sys.stdout = savestdout

# Main program
# 
Example 40
Project: pyblish-win   Author: pyblish   File: h2py.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global filedict
    opts, args = getopt.getopt(sys.argv[1:], 'i:')
    for o, a in opts:
        if o == '-i':
            ignores.append(re.compile(a))
    if not args:
        args = ['-']
    for filename in args:
        if filename == '-':
            sys.stdout.write('# Generated by h2py from stdin\n')
            process(sys.stdin, sys.stdout)
        else:
            fp = open(filename, 'r')
            outfile = os.path.basename(filename)
            i = outfile.rfind('.')
            if i > 0: outfile = outfile[:i]
            modname = outfile.upper()
            outfile = modname + '.py'
            outfp = open(outfile, 'w')
            outfp.write('# Generated by h2py from %s\n' % filename)
            filedict = {}
            for dir in searchdirs:
                if filename[:len(dir)] == dir:
                    filedict[filename[len(dir)+1:]] = None  # no '/' trailing
                    importable[filename[len(dir)+1:]] = modname
                    break
            process(fp, outfp)
            outfp.close()
            fp.close() 
Example 41
Project: pyblish-win   Author: pyblish   File: nm2def.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():

    s = symbols(PYTHONLIB)
    filter_Python(s)
    exports = export_list(s)
    f = sys.stdout # open('PC/python_nt.def','w')
    f.write(DEF_TEMPLATE % (exports))
    f.close() 
Example 42
Project: pyblish-win   Author: pyblish   File: md5sum.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def printsumfp(fp, filename, out=sys.stdout):
    m = md5.new()
    try:
        while 1:
            data = fp.read(bufsize)
            if not data:
                break
            m.update(data)
    except IOError, msg:
        sys.stderr.write('%s: I/O error: %s\n' % (filename, msg))
        return 1 
Example 43
Project: pyblish-win   Author: pyblish   File: md5sum.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(args = sys.argv[1:], out=sys.stdout):
    global fnfilter, rmode, bufsize
    try:
        opts, args = getopt.getopt(args, 'blts:')
    except getopt.error, msg:
        sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage))
        return 2 
Example 44
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dumpfiles(self, outfile=sys.stdout):
        filelist = self.filenames.values()
        filelist.sort()
        for filename in filelist:
            print>>outfile, filename 
Example 45
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dumpnodes(self, outfile=sys.stdout):
        self.dumped = {}
        if self.nodelist:
            nodename, dummy, dummy, dummy, dummy = self.nodelist[0]
            self.topnode = nodename

        print>>outfile,  '<UL>'
        for node in self.nodelist:
            self.dumpnode(node,0,outfile)
        print>>outfile,  '</UL>' 
Example 46
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dumpmenu(self, menu, indent=0, outfile=sys.stdout):
        if menu:
            currentnode = self.current
            if currentnode != self.topnode:    # XXX this is a hack
                print>>outfile, ' '*indent + '<UL>'
                indent += 2
            for item in menu:
                menunode = self.getnode(item)
                self.dumpnode(menunode,indent,outfile)
            if currentnode != self.topnode:    # XXX this is a hack
                print>>outfile, ' '*indent + '</UL>'
                indent -= 2 
Example 47
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dumpindex(self, outfile=sys.stdout):
        print>>outfile,  '<UL>'
        for (key,location) in self.indexlist:
            key = self.codeexpand(key)
            location = makefile(location)
            location = self.dirname + '/' + location
            print>>outfile, '<LI><OBJECT type="text/sitemap">',
            print>>outfile, '<param name="Name" value="' + key + '">',
            print>>outfile, '<param name="Local" value="' + location + '">',
            print>>outfile, '</OBJECT>'
        print>>outfile,  '</UL>' 
Example 48
Project: pyblish-win   Author: pyblish   File: findlinksto.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '')
        if len(args) < 2:
            raise getopt.GetoptError('not enough arguments', None)
    except getopt.GetoptError, msg:
        sys.stdout = sys.stderr
        print msg
        print 'usage: findlinksto pattern directory ...'
        sys.exit(2) 
Example 49
Project: pyblish-win   Author: pyblish   File: cmd.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def print_topics(self, header, cmds, cmdlen, maxcol):
        if cmds:
            self.stdout.write("%s\n"%str(header))
            if self.ruler:
                self.stdout.write("%s\n"%str(self.ruler * len(header)))
            self.columnize(cmds, maxcol-1)
            self.stdout.write("\n") 
Example 50
Project: pyblish-win   Author: pyblish   File: result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, stream=None, descriptions=None, verbosity=None):
        self.failfast = False
        self.failures = []
        self.errors = []
        self.testsRun = 0
        self.skipped = []
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        self.shouldStop = False
        self.buffer = False
        self._stdout_buffer = None
        self._stderr_buffer = None
        self._original_stdout = sys.stdout
        self._original_stderr = sys.stderr
        self._mirrorOutput = False 
Example 51
Project: pyblish-win   Author: pyblish   File: result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _setupStdout(self):
        if self.buffer:
            if self._stderr_buffer is None:
                self._stderr_buffer = StringIO()
                self._stdout_buffer = StringIO()
            sys.stdout = self._stdout_buffer
            sys.stderr = self._stderr_buffer 
Example 52
Project: pyblish-win   Author: pyblish   File: result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _exc_info_to_string(self, err, test):
        """Converts a sys.exc_info()-style tuple of values into a string."""
        exctype, value, tb = err
        # Skip test runner traceback levels
        while tb and self._is_relevant_tb_level(tb):
            tb = tb.tb_next

        if exctype is test.failureException:
            # Skip assert*() traceback levels
            length = self._count_relevant_tb_levels(tb)
            msgLines = traceback.format_exception(exctype, value, tb, length)
        else:
            msgLines = traceback.format_exception(exctype, value, tb)

        if self.buffer:
            output = sys.stdout.getvalue()
            error = sys.stderr.getvalue()
            if output:
                if not output.endswith('\n'):
                    output += '\n'
                msgLines.append(STDOUT_LINE % output)
            if error:
                if not error.endswith('\n'):
                    error += '\n'
                msgLines.append(STDERR_LINE % error)
        return ''.join(msgLines) 
Example 53
Project: pyblish-win   Author: pyblish   File: test_result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self._real_out = sys.stdout
        self._real_err = sys.stderr 
Example 54
Project: pyblish-win   Author: pyblish   File: test_result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        sys.stdout = self._real_out
        sys.stderr = self._real_err 
Example 55
Project: pyblish-win   Author: pyblish   File: test_result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testBufferOutputOff(self):
        real_out = self._real_out
        real_err = self._real_err

        result = unittest.TestResult()
        self.assertFalse(result.buffer)

        self.assertIs(real_out, sys.stdout)
        self.assertIs(real_err, sys.stderr)

        result.startTest(self)

        self.assertIs(real_out, sys.stdout)
        self.assertIs(real_err, sys.stderr) 
Example 56
Project: pyblish-win   Author: pyblish   File: pstats.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, profile=None):
            cmd.Cmd.__init__(self)
            self.prompt = "% "
            self.stats = None
            self.stream = sys.stdout
            if profile is not None:
                self.do_read(profile) 
Example 57
Project: pyblish-win   Author: pyblish   File: iterators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _structure(msg, fp=None, level=0, include_default=False):
    """A handy debugging aid"""
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print >> fp, tab + msg.get_content_type(),
    if include_default:
        print >> fp, '[%s]' % msg.get_default_type()
    else:
        print >> fp
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, fp, level+1, include_default) 
Example 58
Project: pyblish-win   Author: pyblish   File: driver.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(*args):
    """Main program, when run as a script: produce grammar pickle files.

    Calls load_grammar for each argument, a path to a grammar text file.
    """
    if not args:
        args = sys.argv[1:]
    logging.basicConfig(level=logging.INFO, stream=sys.stdout,
                        format='%(message)s')
    for gt in args:
        load_grammar(gt, save=True, force=True)
    return True 
Example 59
Project: pyblish-win   Author: pyblish   File: test_main.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
        save_stdin = sys.stdin
        save_stdout = sys.stdout
        save_stderr = sys.stderr
        sys.stdin = in_capture
        sys.stdout = out_capture
        sys.stderr = err_capture
        try:
            return main.main("lib2to3.fixes", args)
        finally:
            sys.stdin = save_stdin
            sys.stdout = save_stdout
            sys.stderr = save_stderr 
Example 60
Project: pyblish-win   Author: pyblish   File: telnetlib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_debuglevel(self, debuglevel):
        """Set the debug level.

        The higher it is, the more debug output you get (on sys.stdout).

        """
        self.debuglevel = debuglevel 
Example 61
Project: pyblish-win   Author: pyblish   File: telnetlib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def listener(self):
        """Helper for mt_interact() -- this executes in the other thread."""
        while 1:
            try:
                data = self.read_eager()
            except EOFError:
                print '*** Connection closed by remote host ***'
                return
            if data:
                sys.stdout.write(data)
            else:
                sys.stdout.flush() 
Example 62
Project: pyblish-win   Author: pyblish   File: cgitb.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, display=1, logdir=None, context=5, file=None,
                 format="html"):
        self.display = display          # send tracebacks to browser if true
        self.logdir = logdir            # log tracebacks to files if not None
        self.context = context          # number of source code lines per frame
        self.file = file or sys.stdout  # place to send the output
        self.format = format 
Example 63
Project: pyblish-win   Author: pyblish   File: pprint.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout]."""
    printer = PrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object) 
Example 64
Project: pyblish-win   Author: pyblish   File: cgi.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test(environ=os.environ):
    """Robust test CGI script, usable as main program.

    Write minimal HTTP headers and dump all information provided to
    the script in HTML form.

    """
    print "Content-type: text/html"
    print
    sys.stderr = sys.stdout
    try:
        form = FieldStorage()   # Replace with other classes to test those
        print_directory()
        print_arguments()
        print_form(form)
        print_environ(environ)
        print_environ_usage()
        def f():
            exec "testing print_exception() -- <I>italics?</I>"
        def g(f=f):
            f()
        print "<H3>What follows is a test, not an actual exception:</H3>"
        g()
    except:
        print_exception()

    print "<H1>Second try with a small maxlen...</H1>"

    global maxlen
    maxlen = 50
    try:
        form = FieldStorage()   # Replace with other classes to test those
        print_directory()
        print_arguments()
        print_form(form)
        print_environ(environ)
    except:
        print_exception() 
Example 65
Project: pyblish-win   Author: pyblish   File: log.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _log(self, level, msg, args):
        if level not in (DEBUG, INFO, WARN, ERROR, FATAL):
            raise ValueError('%s wrong log level' % str(level))

        if level >= self.threshold:
            if args:
                msg = msg % args
            if level in (WARN, ERROR, FATAL):
                stream = sys.stderr
            else:
                stream = sys.stdout
            stream.write('%s\n' % msg)
            stream.flush() 
Example 66
Project: pyblish-win   Author: pyblish   File: test_build_ext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_build_ext(self):
        global ALREADY_TESTED
        support.copy_xxmodule_c(self.tmp_dir)
        self.xx_created = True
        xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
        xx_ext = Extension('xx', [xx_c])
        dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
        dist.package_dir = self.tmp_dir
        cmd = build_ext(dist)
        support.fixup_build_ext(cmd)
        cmd.build_lib = self.tmp_dir
        cmd.build_temp = self.tmp_dir

        old_stdout = sys.stdout
        if not test_support.verbose:
            # silence compiler output
            sys.stdout = StringIO()
        try:
            cmd.ensure_finalized()
            cmd.run()
        finally:
            sys.stdout = old_stdout

        if ALREADY_TESTED:
            self.skipTest('Already tested in %s' % ALREADY_TESTED)
        else:
            ALREADY_TESTED = type(self).__name__

        import xx

        for attr in ('error', 'foo', 'new', 'roj'):
            self.assertTrue(hasattr(xx, attr))

        self.assertEqual(xx.foo(2, 5), 7)
        self.assertEqual(xx.foo(13,15), 28)
        self.assertEqual(xx.new().demo(), None)
        if test_support.HAVE_DOCSTRINGS:
            doc = 'This is a template module just for instruction.'
            self.assertEqual(xx.__doc__, doc)
        self.assertIsInstance(xx.Null(), xx.Null)
        self.assertIsInstance(xx.Str(), xx.Str) 
Example 67
Project: pyblish-win   Author: pyblish   File: test_core.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(CoreTestCase, self).setUp()
        self.old_stdout = sys.stdout
        self.cleanup_testfn()
        self.old_argv = sys.argv, sys.argv[:] 
Example 68
Project: pyblish-win   Author: pyblish   File: test_core.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        sys.stdout = self.old_stdout
        self.cleanup_testfn()
        sys.argv = self.old_argv[0]
        sys.argv[:] = self.old_argv[1]
        super(CoreTestCase, self).tearDown() 
Example 69
Project: pyblish-win   Author: pyblish   File: uu.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test():
    """uuencode/uudecode main program"""

    import optparse
    parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
    parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
    parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')

    (options, args) = parser.parse_args()
    if len(args) > 2:
        parser.error('incorrect number of arguments')
        sys.exit(1)

    input = sys.stdin
    output = sys.stdout
    if len(args) > 0:
        input = args[0]
    if len(args) > 1:
        output = args[1]

    if options.decode:
        if options.text:
            if isinstance(output, basestring):
                output = open(output, 'w')
            else:
                print sys.argv[0], ': cannot do -t to stdout'
                sys.exit(1)
        decode(input, output)
    else:
        if options.text:
            if isinstance(input, basestring):
                input = open(input, 'r')
            else:
                print sys.argv[0], ': cannot do -t from stdin'
                sys.exit(1)
        encode(input, output) 
Example 70
Project: pyblish-win   Author: pyblish   File: pydoc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 71
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 4 votes vote down vote up
def main(settings=None, stdout=None, args=None):
    """Execution entry point."""
    parser = get_parser()
    if args is None:
        args = sys.argv[1:]
    args = parser.parse_args(args)

    config = OdorikConfig(args.config_section)
    if settings is None:
        config.load(args.config)
    else:
        for section, key, value in settings:
            config.set(section, key, value)

    for override in ('user', 'password', 'url'):
        value = getattr(args, override)
        if value is not None:
            config.set(args.config_section, override, value)

    command = COMMANDS[args.cmd](args, config, stdout)
    try:
        command.run()
    except (CommandError, odorik.OdorikException) as error:
        print('Error: {0}'.format(error), file=sys.stderr)
        sys.exit(1) 
Example 72
Project: alfred-yubikey-otp   Author: robertoriv   File: background.py    MIT License 4 votes vote down vote up
def _background(pidfile, stdin='/dev/null', stdout='/dev/null',
                stderr='/dev/null'):  # pragma: no cover
    """Fork the current process into a background daemon.

    :param pidfile: file to write PID of daemon process to.
    :type pidfile: filepath
    :param stdin: where to read input
    :type stdin: filepath
    :param stdout: where to write stdout output
    :type stdout: filepath
    :param stderr: where to write stderr output
    :type stderr: filepath

    """
    def _fork_and_exit_parent(errmsg, wait=False, write=False):
        try:
            pid = os.fork()
            if pid > 0:
                if write:  # write PID of child process to `pidfile`
                    tmp = pidfile + '.tmp'
                    with open(tmp, 'wb') as fp:
                        fp.write(str(pid))
                    os.rename(tmp, pidfile)
                if wait:  # wait for child process to exit
                    os.waitpid(pid, 0)
                os._exit(0)
        except OSError as err:
            _log().critical('%s: (%d) %s', errmsg, err.errno, err.strerror)
            raise err

    # Do first fork and wait for second fork to finish.
    _fork_and_exit_parent('fork #1 failed', wait=True)

    # Decouple from parent environment.
    os.chdir(wf().workflowdir)
    os.setsid()

    # Do second fork and write PID to pidfile.
    _fork_and_exit_parent('fork #2 failed', write=True)

    # Now I am a daemon!
    # Redirect standard file descriptors.
    si = open(stdin, 'r', 0)
    so = open(stdout, 'a+', 0)
    se = open(stderr, 'a+', 0)
    if hasattr(sys.stdin, 'fileno'):
        os.dup2(si.fileno(), sys.stdin.fileno())
    if hasattr(sys.stdout, 'fileno'):
        os.dup2(so.fileno(), sys.stdout.fileno())
    if hasattr(sys.stderr, 'fileno'):
        os.dup2(se.fileno(), sys.stderr.fileno()) 
Example 73
Project: pyblish-win   Author: pyblish   File: wcgui.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def __init__(self, parent, root=webchecker.DEFROOT):
        self.__parent = parent

        self.__topcontrols = Frame(parent)
        self.__topcontrols.pack(side=TOP, fill=X)
        self.__label = Label(self.__topcontrols, text="Root URL:")
        self.__label.pack(side=LEFT)
        self.__rootentry = Entry(self.__topcontrols, width=60)
        self.__rootentry.pack(side=LEFT)
        self.__rootentry.bind('<Return>', self.enterroot)
        self.__rootentry.focus_set()

        self.__controls = Frame(parent)
        self.__controls.pack(side=TOP, fill=X)
        self.__running = 0
        self.__start = Button(self.__controls, text="Run", command=self.start)
        self.__start.pack(side=LEFT)
        self.__stop = Button(self.__controls, text="Stop", command=self.stop,
                             state=DISABLED)
        self.__stop.pack(side=LEFT)
        self.__step = Button(self.__controls, text="Check one",
                             command=self.step)
        self.__step.pack(side=LEFT)
        self.__cv = BooleanVar(parent)
        self.__cv.set(self.checkext)
        self.__checkext = Checkbutton(self.__controls, variable=self.__cv,
                                      command=self.update_checkext,
                                      text="Check nonlocal links",)
        self.__checkext.pack(side=LEFT)
        self.__reset = Button(self.__controls, text="Start over", command=self.reset)
        self.__reset.pack(side=LEFT)
        if __name__ == '__main__': # No Quit button under Grail!
            self.__quit = Button(self.__controls, text="Quit",
                                 command=self.__parent.quit)
            self.__quit.pack(side=RIGHT)

        self.__status = Label(parent, text="Status: initial", anchor=W)
        self.__status.pack(side=TOP, fill=X)
        self.__checking = Label(parent, text="Idle", anchor=W)
        self.__checking.pack(side=TOP, fill=X)
        self.__mp = mp = MultiPanel(parent)
        sys.stdout = self.__log = LogPanel(mp, "Log")
        self.__todo = ListPanel(mp, "To check", self, self.showinfo)
        self.__done = ListPanel(mp, "Checked", self, self.showinfo)
        self.__bad = ListPanel(mp, "Bad links", self, self.showinfo)
        self.__errors = ListPanel(mp, "Pages w/ bad links", self, self.showinfo)
        self.__details = LogPanel(mp, "Details")
        self.root_seed = None
        webchecker.Checker.__init__(self)
        if root:
            root = str(root).strip()
            if root:
                self.suggestroot(root)
        self.newstatus() 
Example 74
Project: pyblish-win   Author: pyblish   File: objgraph.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def main():
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
    except getopt.error:
        sys.stdout = sys.stderr
        print 'Usage:', os.path.basename(sys.argv[0]),
        print           '[-cdu] [file] ...'
        print '-c: print callers per objectfile'
        print '-d: print callees per objectfile'
        print '-u: print usage of undefined symbols'
        print 'If none of -cdu is specified, all are assumed.'
        print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),'
        print 'e.g.: nm -o /lib/libc.a | objgraph'
        return 1
    optu = optc = optd = 0
    for opt, void in optlist:
        if opt == '-u':
            optu = 1
        elif opt == '-c':
            optc = 1
        elif opt == '-d':
            optd = 1
    if optu == optc == optd == 0:
        optu = optc = optd = 1
    if not args:
        args = ['-']
    for filename in args:
        if filename == '-':
            readinput(sys.stdin)
        else:
            readinput(open(filename, 'r'))
    #
    warndups()
    #
    more = (optu + optc + optd > 1)
    if optd:
        if more:
            print '---------------All callees------------------'
        printcallee()
    if optu:
        if more:
            print '---------------Undefined callees------------'
        printundef()
    if optc:
        if more:
            print '---------------All Callers------------------'
        printcaller()
    return 0

# Call the main program.
# Use its return value as exit status.
# Catch interrupts to avoid stack trace.
# 
Example 75
Project: pyblish-win   Author: pyblish   File: cmd.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey+": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass 
Example 76
Project: pyblish-win   Author: pyblish   File: cmd.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def do_help(self, arg):
        'List available commands with "help" or detailed help with "help cmd".'
        if arg:
            # XXX check arg syntax
            try:
                func = getattr(self, 'help_' + arg)
            except AttributeError:
                try:
                    doc=getattr(self, 'do_' + arg).__doc__
                    if doc:
                        self.stdout.write("%s\n"%str(doc))
                        return
                except AttributeError:
                    pass
                self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
                return
            func()
        else:
            names = self.get_names()
            cmds_doc = []
            cmds_undoc = []
            help = {}
            for name in names:
                if name[:5] == 'help_':
                    help[name[5:]]=1
            names.sort()
            # There can be duplicates if routines overridden
            prevname = ''
            for name in names:
                if name[:3] == 'do_':
                    if name == prevname:
                        continue
                    prevname = name
                    cmd=name[3:]
                    if cmd in help:
                        cmds_doc.append(cmd)
                        del help[cmd]
                    elif getattr(self, name).__doc__:
                        cmds_doc.append(cmd)
                    else:
                        cmds_undoc.append(cmd)
            self.stdout.write("%s\n"%str(self.doc_leader))
            self.print_topics(self.doc_header,   cmds_doc,   15,80)
            self.print_topics(self.misc_header,  help.keys(),15,80)
            self.print_topics(self.undoc_header, cmds_undoc, 15,80) 
Example 77
Project: pyblish-win   Author: pyblish   File: cmd.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def columnize(self, list, displaywidth=80):
        """Display a list of strings as a compact set of columns.

        Each column is only as wide as necessary.
        Columns are separated by two spaces (one was not legible enough).
        """
        if not list:
            self.stdout.write("<empty>\n")
            return
        nonstrings = [i for i in range(len(list))
                        if not isinstance(list[i], str)]
        if nonstrings:
            raise TypeError, ("list[i] not a string for i in %s" %
                              ", ".join(map(str, nonstrings)))
        size = len(list)
        if size == 1:
            self.stdout.write('%s\n'%str(list[0]))
            return
        # Try every row count from 1 upwards
        for nrows in range(1, len(list)):
            ncols = (size+nrows-1) // nrows
            colwidths = []
            totwidth = -2
            for col in range(ncols):
                colwidth = 0
                for row in range(nrows):
                    i = row + nrows*col
                    if i >= size:
                        break
                    x = list[i]
                    colwidth = max(colwidth, len(x))
                colwidths.append(colwidth)
                totwidth += colwidth + 2
                if totwidth > displaywidth:
                    break
            if totwidth <= displaywidth:
                break
        else:
            nrows = len(list)
            ncols = 1
            colwidths = [0]
        for row in range(nrows):
            texts = []
            for col in range(ncols):
                i = row + nrows*col
                if i >= size:
                    x = ""
                else:
                    x = list[i]
                texts.append(x)
            while texts and not texts[-1]:
                del texts[-1]
            for col in range(len(texts)):
                texts[col] = texts[col].ljust(colwidths[col])
            self.stdout.write("%s\n"%str("  ".join(texts))) 
Example 78
Project: pyblish-win   Author: pyblish   File: test_result.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def testBufferOutputStartTestAddSuccess(self):
        real_out = self._real_out
        real_err = self._real_err

        result = unittest.TestResult()
        self.assertFalse(result.buffer)

        result.buffer = True

        self.assertIs(real_out, sys.stdout)
        self.assertIs(real_err, sys.stderr)

        result.startTest(self)

        self.assertIsNot(real_out, sys.stdout)
        self.assertIsNot(real_err, sys.stderr)
        self.assertIsInstance(sys.stdout, StringIO)
        self.assertIsInstance(sys.stderr, StringIO)
        self.assertIsNot(sys.stdout, sys.stderr)

        out_stream = sys.stdout
        err_stream = sys.stderr

        result._original_stdout = StringIO()
        result._original_stderr = StringIO()

        print 'foo'
        print >> sys.stderr, 'bar'

        self.assertEqual(out_stream.getvalue(), 'foo\n')
        self.assertEqual(err_stream.getvalue(), 'bar\n')

        self.assertEqual(result._original_stdout.getvalue(), '')
        self.assertEqual(result._original_stderr.getvalue(), '')

        result.addSuccess(self)
        result.stopTest(self)

        self.assertIs(sys.stdout, result._original_stdout)
        self.assertIs(sys.stderr, result._original_stderr)

        self.assertEqual(result._original_stdout.getvalue(), '')
        self.assertEqual(result._original_stderr.getvalue(), '')

        self.assertEqual(out_stream.getvalue(), '')
        self.assertEqual(err_stream.getvalue(), '') 
Example 79
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def basicConfig(**kwargs):
    """
    Do basic configuration for the logging system.

    This function does nothing if the root logger already has handlers
    configured. It is a convenience method intended for use by simple scripts
    to do one-shot configuration of the logging package.

    The default behaviour is to create a StreamHandler which writes to
    sys.stderr, set a formatter using the BASIC_FORMAT format string, and
    add the handler to the root logger.

    A number of optional keyword arguments may be specified, which can alter
    the default behaviour.

    filename  Specifies that a FileHandler be created, using the specified
              filename, rather than a StreamHandler.
    filemode  Specifies the mode to open the file, if filename is specified
              (if filemode is unspecified, it defaults to 'a').
    format    Use the specified format string for the handler.
    datefmt   Use the specified date/time format.
    level     Set the root logger level to the specified level.
    stream    Use the specified stream to initialize the StreamHandler. Note
              that this argument is incompatible with 'filename' - if both
              are present, 'stream' is ignored.

    Note that you could specify a stream created using open(filename, mode)
    rather than passing the filename and mode in. However, it should be
    remembered that StreamHandler does not close its stream (since it may be
    using sys.stdout or sys.stderr), whereas FileHandler closes its stream
    when the handler is closed.
    """
    # Add thread safety in case someone mistakenly calls
    # basicConfig() from multiple threads
    _acquireLock()
    try:
        if len(root.handlers) == 0:
            filename = kwargs.get("filename")
            if filename:
                mode = kwargs.get("filemode", 'a')
                hdlr = FileHandler(filename, mode)
            else:
                stream = kwargs.get("stream")
                hdlr = StreamHandler(stream)
            fs = kwargs.get("format", BASIC_FORMAT)
            dfs = kwargs.get("datefmt", None)
            fmt = Formatter(fs, dfs)
            hdlr.setFormatter(fmt)
            root.addHandler(hdlr)
            level = kwargs.get("level")
            if level is not None:
                root.setLevel(level)
    finally:
        _releaseLock()

#---------------------------------------------------------------------------
# Utility functions at module level.
# Basically delegate everything to the root logger.
#--------------------------------------------------------------------------- 
Example 80
Project: pyblish-win   Author: pyblish   File: uu.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def encode(in_file, out_file, name=None, mode=None):
    """Uuencode file"""
    #
    # If in_file is a pathname open it and change defaults
    #
    opened_files = []
    try:
        if in_file == '-':
            in_file = sys.stdin
        elif isinstance(in_file, basestring):
            if name is None:
                name = os.path.basename(in_file)
            if mode is None:
                try:
                    mode = os.stat(in_file).st_mode
                except AttributeError:
                    pass
            in_file = open(in_file, 'rb')
            opened_files.append(in_file)
        #
        # Open out_file if it is a pathname
        #
        if out_file == '-':
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            out_file = open(out_file, 'wb')
            opened_files.append(out_file)
        #
        # Set defaults for name and mode
        #
        if name is None:
            name = '-'
        if mode is None:
            mode = 0666
        #
        # Write the data
        #
        out_file.write('begin %o %s\n' % ((mode&0777),name))
        data = in_file.read(45)
        while len(data) > 0:
            out_file.write(binascii.b2a_uu(data))
            data = in_file.read(45)
        out_file.write(' \nend\n')
    finally:
        for f in opened_files:
            f.close()