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 8 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