Python sys.stderr() Examples

The following are code examples for showing how to use sys.stderr(). 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: mlbv   Author: kmac   File: util.py    GNU General Public License v3.0 7 votes vote down vote up
def init_logging(log_file=None, append=False, console_loglevel=logging.INFO):
    """Set up logging to file and console."""
    if log_file is not None:
        if append:
            filemode_val = 'a'
        else:
            filemode_val = 'w'
        logging.basicConfig(level=logging.DEBUG,
                            format="%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s",
                            # datefmt='%m-%d %H:%M',
                            filename=log_file,
                            filemode=filemode_val)
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(console_loglevel)
    # set a format which is simpler for console use
    formatter = logging.Formatter("%(message)s")
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)
    global LOG
    LOG = logging.getLogger(__name__) 
Example 2
Project: pyblish-win   Author: pyblish   File: trace.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def main(argv=None):
    import getopt

    if argv is None:
        argv = sys.argv
    try:
        opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
                                        ["help", "version", "trace", "count",
                                         "report", "no-report", "summary",
                                         "file=", "missing",
                                         "ignore-module=", "ignore-dir=",
                                         "coverdir=", "listfuncs",
                                         "trackcalls", "timing"])

    except getopt.error, msg:
        sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
        sys.stderr.write("Try `%s --help' for more information\n"
                         % sys.argv[0])
        sys.exit(1) 
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: Switchboard.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []
        self.__red = 0
        self.__green = 0
        self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile)
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, DictType):
                        print >> sys.stderr, \
                              'Problem reading options from file:', initfile
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):
                    pass
            finally:
                if fp:
                    fp.close() 
Example 7
Project: pyblish-win   Author: pyblish   File: Switchboard.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def save_views(self):
        # save the current color
        self.__optiondb['RED'] = self.__red
        self.__optiondb['GREEN'] = self.__green
        self.__optiondb['BLUE'] = self.__blue
        for v in self.__views:
            if hasattr(v, 'save_options'):
                v.save_options(self.__optiondb)
        # save the name of the file used for the color database.  we'll try to
        # load this first.
        self.__optiondb['DBFILE'] = self.__colordb.filename()
        fp = None
        try:
            try:
                fp = open(self.__initfile, 'w')
            except IOError:
                print >> sys.stderr, 'Cannot write options to file:', \
                      self.__initfile
            else:
                marshal.dump(self.__optiondb, fp)
        finally:
            if fp:
                fp.close() 
Example 8
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_backup(filename):
    import os, os.path
    backup = filename + '~'
    if os.path.lexists(backup):
        try:
            os.remove(backup)
        except os.error:
            print("Can't remove backup %r" % (backup,), file=sys.stderr)
        # end try
    # end if
    try:
        os.rename(filename, backup)
    except os.error:
        print("Can't rename %r to %r" % (filename, backup), file=sys.stderr)
    # end try
# end def make_backup 
Example 9
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 10
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 11
Project: pyblish-win   Author: pyblish   File: pygettext.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __openseen(self, ttype, tstring, lineno):
        if ttype == tokenize.OP and tstring == ')':
            # We've seen the last of the translatable strings.  Record the
            # line number of the first line of the strings and update the list
            # of messages seen.  Reset state for the next batch.  If there
            # were no strings inside _(), then just ignore this entry.
            if self.__data:
                self.__addentry(EMPTYSTRING.join(self.__data))
            self.__state = self.__waiting
        elif ttype == tokenize.STRING:
            self.__data.append(safe_eval(tstring))
        elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
                           token.NEWLINE, tokenize.NL]:
            # warn if we see anything else than STRING or whitespace
            print >> sys.stderr, _(
                '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
                ) % {
                'token': tstring,
                'file': self.__curfile,
                'lineno': self.__lineno
                }
            self.__state = self.__waiting 
Example 12
Project: pyblish-win   Author: pyblish   File: msgfmt.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make(filename, outfile):
    ID = 1
    STR = 2

    # Compute .mo name from .po name and arguments
    if filename.endswith('.po'):
        infile = filename
    else:
        infile = filename + '.po'
    if outfile is None:
        outfile = os.path.splitext(infile)[0] + '.mo'

    try:
        lines = open(infile).readlines()
    except IOError, msg:
        print >> sys.stderr, msg
        sys.exit(1) 
Example 13
Project: pyblish-win   Author: pyblish   File: traceback.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def print_exception(etype, value, tb, limit=None, file=None):
    """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.

    This differs from print_tb() in the following ways: (1) if
    traceback is not None, it prints a header "Traceback (most recent
    call last):"; (2) it prints the exception type and value after the
    stack trace; (3) if type is SyntaxError and value has the
    appropriate format, it prints the line where the syntax error
    occurred with a caret on the next line indicating the approximate
    position of the error.
    """
    if file is None:
        file = sys.stderr
    if tb:
        _print(file, 'Traceback (most recent call last):')
        print_tb(tb, limit, file)
    lines = format_exception_only(etype, value)
    for line in lines:
        _print(file, line, '') 
Example 14
Project: pyblish-win   Author: pyblish   File: test_main.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_filename_changing_on_output_two_files(self):
        """2to3 two files in one directory with a new output dir."""
        self.setup_test_source_trees()
        err = StringIO.StringIO()
        py2_files = [self.trivial_py2_file, self.init_py2_file]
        expected_files = set(os.path.basename(name) for name in py2_files)
        ret = self.run_2to3_capture(
                ["-n", "-w", "--write-unchanged-files",
                 "--no-diffs", "--output-dir", self.py3_dest_dir] + py2_files,
                StringIO.StringIO(""), StringIO.StringIO(), err)
        self.assertEqual(ret, 0)
        stderr = err.getvalue()
        self.assertIn(
                "Output in %r will mirror the input directory %r layout" % (
                        self.py3_dest_dir, self.py2_src_dir), stderr)
        self.assertEqual(expected_files, set(os.listdir(self.py3_dest_dir))) 
Example 15
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_tests(package, mask, verbosity, exclude=()):
    """Return a list of skipped test modules, and a list of test cases."""
    tests = []
    skipped = []
    for modname in find_package_modules(package, mask):
        if modname.split(".")[-1] in exclude:
            skipped.append(modname)
            if verbosity > 1:
                print >> sys.stderr, "Skipped %s: excluded" % modname
            continue
        try:
            mod = __import__(modname, globals(), locals(), ['*'])
        except (ResourceDenied, unittest.SkipTest) as detail:
            skipped.append(modname)
            if verbosity > 1:
                print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
            continue
        for name in dir(mod):
            if name.startswith("_"):
                continue
            o = getattr(mod, name)
            if type(o) is type(unittest.TestCase) and issubclass(o, unittest.TestCase):
                tests.append(o)
    return skipped, tests 
Example 16
Project: pyblish-win   Author: pyblish   File: atexit.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _run_exitfuncs():
    """run any registered exit functions

    _exithandlers is traversed in reverse order so functions are executed
    last in, first out.
    """

    exc_info = None
    while _exithandlers:
        func, targs, kargs = _exithandlers.pop()
        try:
            func(*targs, **kargs)
        except SystemExit:
            exc_info = sys.exc_info()
        except:
            import traceback
            print >> sys.stderr, "Error in atexit._run_exitfuncs:"
            traceback.print_exc()
            exc_info = sys.exc_info()

    if exc_info is not None:
        raise exc_info[0], exc_info[1], exc_info[2] 
Example 17
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def callHandlers(self, record):
        """
        Pass a record to all relevant handlers.

        Loop through all handlers for this logger and its parents in the
        logger hierarchy. If no handler was found, output a one-off error
        message to sys.stderr. Stop searching up the hierarchy whenever a
        logger with the "propagate" attribute set to zero is found - that
        will be the last logger whose handlers are called.
        """
        c = self
        found = 0
        while c:
            for hdlr in c.handlers:
                found = found + 1
                if record.levelno >= hdlr.level:
                    hdlr.handle(record)
            if not c.propagate:
                c = None    #break out
            else:
                c = c.parent
        if (found == 0) and raiseExceptions and not self.manager.emittedNoHandlerWarning:
            sys.stderr.write("No handlers could be found for logger"
                             " \"%s\"\n" % self.name)
            self.manager.emittedNoHandlerWarning = 1 
Example 18
Project: fs_image   Author: facebookincubator   File: dump_sendstream.py    MIT License 5 votes vote down vote up
def main(argv):
    if len(argv) != 1:
        print(__doc__, file=sys.stderr)
        return 1

    for item in parse_send_stream(sys.stdin.buffer):
        print(item) 
Example 19
Project: fs_image   Author: facebookincubator   File: sendstream_has_loop_device.py    MIT License 5 votes vote down vote up
def main(argv):
    if len(argv) != 1:
        print(__doc__, file=sys.stderr)
        return 1
    for item in parse_send_stream(sys.stdin.buffer):
        if isinstance(item, SendStreamItems.mknod) and (
            os.major(item.dev) == 7 or item.dev == os.makedev(10, 237)
        ):
            # Not printing the path here since it'd be `o123-78-456` or some
            # similarly meaningless temporary emitted by `btrfs send`.
            #
            # To get the path, we would instead apply the send-stream to a
            # `Subvolume`, and use `.inodes()` to look for loops.  The
            # downside of that style of check is that it requires us to
            # process a sequence of send-streams in dependency order (or
            # we'd hit dependency errors), whereas just scanning the
            # send-stream is cheap.
            #
            # There are a couple of other approaches to getting the path:
            #  -  Roll some special logic for resolving what names
            #     send-stream temporaries ultimately map to.  Probably not
            #     worth it.
            #  -  Add the capability to `Subvolume` to apply items even when
            #     the dependency is not there, and instead to record some
            #     kind of placeholder / dependency object in the tree.  The
            #     semantics would take some thought to get right, but the
            #     upside is significant, since we would then be able to
            #     handle filesystem diffs almost as easily as full
            #     filesystems.
            print(os.major(item.dev), os.minor(item.dev))
            return 0
    return 2  # Python would return 1 on raised parse exceptions :) 
Example 20
Project: fs_image   Author: facebookincubator   File: print_gold_demo_sendstreams.py    MIT License 5 votes vote down vote up
def main(argv):
    if len(argv) != 2:
        print(__doc__, file=sys.stderr)
        return 1

    with open(os.path.join(
        os.path.dirname(__file__), 'gold_demo_sendstreams.pickle',
    ), "rb") as infile:
        sys.stdout.buffer.write(pickle.load(infile)[argv[1]]["sendstream"])
    return 0 
Example 21
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 5 votes vote down vote up
def _make_socket_and_send_via(*, unix_sock_fd):
    '''
    Creates a TCP stream socket and sends it elsewhere via the provided Unix
    domain socket file descriptor.  This is useful for obtaining a socket
    that belongs to a different network namespace (i.e.  creating a socket
    inside a container, but binding it from outside the container).

    IMPORTANT: This code must not write anything to stdout, the fd can be 1.
    '''
    # NB: Some code here is (sort of) copy-pasta'd in `send_fds_and_run.py`,
    # but it's not obviously worthwhile to reuse it here.
    return ['python3', '-c', textwrap.dedent('''\
    import array, socket, sys

    def send_fds(sock, msg: bytes, fds: 'List[int]'):
        num_sent = sock.sendmsg([msg], [(
            socket.SOL_SOCKET, socket.SCM_RIGHTS,
            array.array('i', fds).tobytes(),
            # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
        )])
        assert len(msg) == num_sent, (msg, num_sent)

    # Make a socket in this netns, and send it to the parent.
    with socket.socket(fileno=''' + str(unix_sock_fd) + ''') as lsock:
        print(f'Sending FD to parent', file=sys.stderr)
        lsock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
        with lsock.accept()[0] as csock, socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ) as inet_sock:
            csock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
            send_fds(csock, b'ohai', [inet_sock.fileno()])
    ''')] 
Example 22
Project: fs_image   Author: facebookincubator   File: rpm_build.py    MIT License 5 votes vote down vote up
def get_phase_builder(
        cls, items: Iterable['RpmBuildItem'], layer_opts: LayerOpts,
    ):
        item, = items
        assert isinstance(item, RpmBuildItem), item

        def builder(subvol: Subvol):
            # For rpmbuild:
            #   - define _topdir to move where the RPM gets built
            #   - use -bb so it only builds from the specfile
            #   - define _rpmfilename to strip version from the result files
            build_cmd = (
                f"rpmbuild --define '_topdir {item.rpmbuild_dir}' "
                    "--define '_rpmfilename %%{NAME}.rpm' "
                    f"-bb {item.rpmbuild_dir}/SPECS/specfile.spec"
            )

            opts = nspawn_in_subvol_parse_opts([
                '--layer', 'UNUSED',
                '--user', 'root',
                '--no-snapshot',
                '--',
                'sh', '-c', f'{build_cmd}',
            ])
            nspawn_in_subvol(subvol, opts, stdout=sys.stderr)

        return builder 
Example 23
Project: leapp-repository   Author: oamg   File: rhel_upgrade.py    Apache License 2.0 5 votes vote down vote up
def _process_packages(self, pkg_set, op):
        '''
        Adds list of packages for given operation to the transaction
        '''
        pkgs_notfound = []

        for pkg_spec in pkg_set:
            try:
                op(pkg_spec)
            except dnf.exceptions.MarkingError:
                pkgs_notfound.append(pkg_spec)
        if pkgs_notfound:
            err_str = ('Packages marked by Leapp for {} not found '
                       'in repositories metadata: '.format(op.__name__) + ' '.join(pkgs_notfound))
            print('Warning: ' + err_str, file=sys.stderr) 
Example 24
Project: leapp-repository   Author: oamg   File: rhel_upgrade.py    Apache License 2.0 5 votes vote down vote up
def run(self):
        # takes local rpms, creates Package objects from them, and then adds them to the sack as virtual repository
        local_rpm_objects = self.base.add_remote_rpms(self.plugin_data['pkgs_info']['local_rpms'])

        for pkg in local_rpm_objects:
            self.base.package_install(pkg)

        to_install = self.plugin_data['pkgs_info']['to_install']
        to_remove = self.plugin_data['pkgs_info']['to_remove']
        to_upgrade = self.plugin_data['pkgs_info']['to_upgrade']

        # Packages to be removed
        self._process_packages(to_remove, self.base.remove)
        # Packages to be installed
        self._process_packages(to_install, self.base.install)
        # Packages to be upgraded
        self._process_packages(to_upgrade, self.base.upgrade)

        self.base.distro_sync()

        if self.opts.tid[0] == 'check':
            try:
                self.base.resolve(allow_erasing=self.cli.demands.allow_erasing)
            except dnf.exceptions.DepsolveError as e:
                print('Transaction check: ', file=sys.stderr)
                print(str(e), file=sys.stderr)
                raise

            # We are doing this to avoid downloading the packages in the check phase
            self.base.download_packages = _do_not_download_packages
            try:
                displays = []
                if self.cli.demands.transaction_display is not None:
                    displays.append(self.cli.demands.transaction_display)
                self.base.do_transaction(display=displays)
            except DoNotDownload:
                print('Check completed.') 
Example 25
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 26
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 27
Project: clikit   Author: sdispater   File: error_output_stream.py    MIT License 5 votes vote down vote up
def __init__(self):  # type: () -> None
        super(ErrorOutputStream, self).__init__(sys.stderr) 
Example 28
Project: chainer-openai-transformer-lm   Author: soskek   File: utils.py    MIT License 5 votes vote down vote up
def iter_data(
    *datas,
    n_batch=128,
    truncate=False,
    verbose=False,
        max_batches=float("inf")):
    n = len(datas[0])
    if truncate:
        n = (n // n_batch) * n_batch
    n = min(n, max_batches * n_batch)
    n_batches = 0
    if verbose:
        f = sys.stderr
    else:
        f = open(os.devnull, 'w')
    for i in tqdm(
            range(
                0,
                n,
                n_batch),
            total=n //
            n_batch,
            file=f,
            ncols=80,
            leave=False):
        if n_batches >= max_batches:
            raise StopIteration
        if len(datas) == 1:
            yield datas[0][i:i + n_batch]
        else:
            yield (d[i:i + n_batch] for d in datas)
        n_batches += 1 
Example 29
Project: alfred-yubikey-otp   Author: robertoriv   File: notify.py    MIT License 5 votes vote down vote up
def convert_image(inpath, outpath, size):
    """Convert an image file using ``sips``.

    Args:
        inpath (str): Path of source file.
        outpath (str): Path to destination file.
        size (int): Width and height of destination image in pixels.

    Raises:
        RuntimeError: Raised if ``sips`` exits with non-zero status.
    """
    cmd = [
        b'sips',
        b'-z', str(size), str(size),
        inpath,
        b'--out', outpath]
    # log().debug(cmd)
    with open(os.devnull, 'w') as pipe:
        retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)

    if retcode != 0:
        raise RuntimeError('sips exited with %d' % retcode) 
Example 30
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow.py    MIT License 5 votes vote down vote up
def _call_security(self, action, service, account, *args):
        """Call ``security`` CLI program that provides access to keychains.

        May raise `PasswordNotFound`, `PasswordExists` or `KeychainError`
        exceptions (the first two are subclasses of `KeychainError`).

        :param action: The ``security`` action to call, e.g.
                           ``add-generic-password``
        :type action: ``unicode``
        :param service: Name of the service.
        :type service: ``unicode``
        :param account: name of the account the password is for, e.g.
            "Pinboard"
        :type account: ``unicode``
        :param password: the password to secure
        :type password: ``unicode``
        :param *args: list of command line arguments to be passed to
                      ``security``
        :type *args: `list` or `tuple`
        :returns: ``(retcode, output)``. ``retcode`` is an `int`, ``output`` a
                  ``unicode`` string.
        :rtype: `tuple` (`int`, ``unicode``)

        """
        cmd = ['security', action, '-s', service, '-a', account] + list(args)
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        stdout, _ = p.communicate()
        if p.returncode == 44:  # password does not exist
            raise PasswordNotFound()
        elif p.returncode == 45:  # password already exists
            raise PasswordExists()
        elif p.returncode > 0:
            err = KeychainError('Unknown Keychain error : %s' % stdout)
            err.retcode = p.returncode
            raise err
        return stdout.strip().decode('utf-8') 
Example 31
Project: phrydy   Author: Josef-Friedrich   File: versioneer.py    MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example 32
Project: tmx2map   Author: joshuaskelly   File: tmx2map.py    MIT License 5 votes vote down vote up
def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(1) 
Example 33
Project: tmx2map   Author: joshuaskelly   File: tmx2map.py    MIT License 5 votes vote down vote up
def report_error():
    error_type, error_value, error_traceback = sys.exc_info()

    if error_traceback.tb_next:
        error_traceback = error_traceback.tb_next

    filename = os.path.normpath(error_traceback.tb_frame.f_code.co_filename)
    error_message = "ERROR: {}:{}: {}: {}".format(filename,
                                                  error_traceback.tb_lineno,
                                                  error_type.__name__,
                                                  error_value)
    print(error_message, file=sys.stderr) 
Example 34
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 35
Project: pyblish-win   Author: pyblish   File: ColorDB.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, fp):
        lineno = 2
        self.__name = fp.name
        # Maintain several dictionaries for indexing into the color database.
        # Note that while Tk supports RGB intensities of 4, 8, 12, or 16 bits,
        # for now we only support 8 bit intensities.  At least on OpenWindows,
        # all intensities in the /usr/openwin/lib/rgb.txt file are 8-bit
        #
        # key is (red, green, blue) tuple, value is (name, [aliases])
        self.__byrgb = {}
        # key is name, value is (red, green, blue)
        self.__byname = {}
        # all unique names (non-aliases).  built-on demand
        self.__allnames = None
        for line in fp:
            # get this compiled regular expression from derived class
            mo = self._re.match(line)
            if not mo:
                print >> sys.stderr, 'Error in', fp.name, ' line', lineno
                lineno += 1
                continue
            # extract the red, green, blue, and name
            red, green, blue = self._extractrgb(mo)
            name = self._extractname(mo)
            keyname = name.lower()
            # BAW: for now the `name' is just the first named color with the
            # rgb values we find.  Later, we might want to make the two word
            # version the `name', or the CapitalizedVersion, etc.
            key = (red, green, blue)
            foundname, aliases = self.__byrgb.get(key, (name, []))
            if foundname <> name and foundname not in aliases:
                aliases.append(name)
            self.__byrgb[key] = (foundname, aliases)
            # add to byname lookup
            self.__byname[keyname] = key
            lineno = lineno + 1

    # override in derived classes 
Example 36
Project: pyblish-win   Author: pyblish   File: reindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def errprint(*args):
    sep = ""
    for arg in args:
        sys.stderr.write(sep + str(arg))
        sep = " "
    sys.stderr.write("\n") 
Example 37
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def error(self, fmt, *args):
        if args: fmt = fmt % args
        # end if
        sys.stderr.write('Error at line %d: %s\n' % (self.lineno, fmt))
        self.write('### %s ###\n' % fmt)
    # end def error 
Example 38
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete(self):
        begin_counter = 0
        end_counter = 0
        while True:
            line = self.getline()
            if not line: break      # EOF
            # end if
            m = self.endprog.match(line)
            if m:
                end_counter += 1
                continue
            # end if
            m = self.kwprog.match(line)
            if m:
                kw = m.group('kw')
                if kw in start:
                    begin_counter += 1
                # end if
            # end if
            self.write(line)
        # end while
        if begin_counter - end_counter < 0:
            sys.stderr.write('Warning: input contained more end tags than expected\n')
        elif begin_counter - end_counter > 0:
            sys.stderr.write('Warning: input contained less end tags than expected\n')
        # end if
    # end def delete 
Example 39
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def error_both(op1, op2):
    sys.stderr.write('Error: You can not specify both '+op1+' and -'+op2[0]+' at the same time\n')
    sys.stderr.write(usage)
    sys.exit(2)
# end def error_both 
Example 40
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 41
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 42
Project: pyblish-win   Author: pyblish   File: fixdiv.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def usage(msg):
    sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
    sys.stderr.write("Usage: %s [-m] warnings\n" % sys.argv[0])
    sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0]) 
Example 43
Project: pyblish-win   Author: pyblish   File: fixdiv.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readwarnings(warningsfile):
    prog = re.compile(PATTERN)
    try:
        f = open(warningsfile)
    except IOError, msg:
        sys.stderr.write("can't open: %s\n" % msg)
        return 
Example 44
Project: pyblish-win   Author: pyblish   File: rgrep.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def usage(msg, code=2):
    sys.stdout = sys.stderr
    print msg
    print __doc__
    sys.exit(code) 
Example 45
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 46
Project: pyblish-win   Author: pyblish   File: pygettext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def usage(code, msg=''):
    print >> sys.stderr, __doc__ % globals()
    if msg:
        print >> sys.stderr, msg
    sys.exit(code) 
Example 47
Project: pyblish-win   Author: pyblish   File: msgfmt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def usage(code, msg=''):
    print >> sys.stderr, __doc__
    if msg:
        print >> sys.stderr, msg
    sys.exit(code) 
Example 48
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 49
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 50
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)