Python sys.version_info() Examples

The following are code examples for showing how to use sys.version_info(). 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: Gurux.DLMS.Python   Author: Gurux   File: GXManufacturerCollection.py    GNU General Public License v2.0 6 votes vote down vote up
def isUpdatesAvailable(cls, path):
        if sys.version_info < (3, 0):
            return False
        # pylint: disable=broad-except
        if not os.path.isfile(os.path.join(path, "files.xml")):
            return True
        try:
            available = dict()
            for it in ET.parse(os.path.join(path, "files.xml")).iter():
                if it.tag == "File":
                    available[it.text] = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")

            path = NamedTemporaryFile()
            path.close()
            urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path.name)
            for it in ET.parse(path.name).iter():
                if it.tag == "File":
                    tmp = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
                    if not it.text in available or available[it.text] != tmp:
                        return True
        except Exception as e:
            print(e)
            return True
        return False 
Example 2
Project: Gurux.DLMS.Python   Author: Gurux   File: GXManufacturerCollection.py    GNU General Public License v2.0 6 votes vote down vote up
def updateManufactureSettings(cls, directory):
        #
        # Update manufacturer settings from the Gurux www server.
        #
        # directory: Target directory.
        #
        if sys.version_info >= (3, 0):
            return
        if not os.path.isdir(directory):
            os.mkdir(directory)
            if not os.path.isdir(directory):
                return
        path = os.path.join(directory, "files.xml")
        urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path)
        for it in ET.parse(path).iter():
            if it.tag == "File":
                path = os.path.join(directory, it.text)
                urllib.request.urlretrieve("https://www.gurux.fi/obis/" + it.text, path) 
Example 3
Project: Gurux.DLMS.Python   Author: Gurux   File: GXByteBuffer.py    GNU General Public License v2.0 6 votes vote down vote up
def hex(cls, value, addSpace=True, index=0, count=None):
        """
        Convert byte array to hex string.
        """
        #Return empty string if array is empty.
        if not value:
            return ""
        hexChars = ""
        #Python 2.7 handles bytes as a string array. It's changed to bytearray.
        if sys.version_info < (3, 0) and not isinstance(value, bytearray):
            value = bytearray(value)
        if count == 0:
            count = len(value)
        for it in value[index:count]:
            hexChars += GXByteBuffer.__HEX_ARRAY[it >> GXByteBuffer.__NIBBLE]
            hexChars += GXByteBuffer.__HEX_ARRAY[it & GXByteBuffer.__LOW_BYTE_PART]
            if addSpace:
                hexChars += ' '
        return hexChars 
Example 4
Project: odorik   Author: nijel   File: test_main.py    GNU General Public License v3.0 6 votes vote down vote up
def execute(args, binary=False, settings=None, stdout=None):
    """Execute command and return output."""
    if settings is None:
        settings = ()
    elif not settings:
        settings = None
    if binary and sys.version_info < (3, 0):
        output = BytesIO()
    else:
        output = StringIO()
    backup = sys.stdout
    try:
        sys.stdout = output
        if stdout:
            stdout = output
        main(args=args, settings=settings, stdout=stdout)
    finally:
        sys.stdout = backup
    return output.getvalue() 
Example 5
Project: pyblish-win   Author: pyblish   File: driver.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def load_grammar(gt="Grammar.txt", gp=None,
                 save=True, force=False, logger=None):
    """Load the grammar (maybe from a pickle)."""
    if logger is None:
        logger = logging.getLogger()
    if gp is None:
        head, tail = os.path.splitext(gt)
        if tail == ".txt":
            tail = ""
        gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
    if force or not _newer(gp, gt):
        logger.info("Generating grammar tables from %s", gt)
        g = pgen.generate_grammar(gt)
        if save:
            logger.info("Writing grammar tables to %s", gp)
            try:
                g.dump(gp)
            except IOError, e:
                logger.info("Writing failed:"+str(e)) 
Example 6
Project: pyblish-win   Author: pyblish   File: sysconfig.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _getuserbase():
    env_base = os.environ.get("PYTHONUSERBASE", None)
    def joinuser(*args):
        return os.path.expanduser(os.path.join(*args))

    # what about 'os2emx', 'riscos' ?
    if os.name == "nt":
        base = os.environ.get("APPDATA") or "~"
        return env_base if env_base else joinuser(base, "Python")

    if sys.platform == "darwin":
        framework = get_config_var("PYTHONFRAMEWORK")
        if framework:
            return env_base if env_base else \
                               joinuser("~", "Library", framework, "%d.%d"
                                            % (sys.version_info[:2]))

    return env_base if env_base else joinuser("~", ".local") 
Example 7
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_record(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(py_modules=['hello'],
                                             scripts=['sayhi'])
        os.chdir(project_dir)
        self.write_file('hello.py', "def main(): print 'o hai'")
        self.write_file('sayhi', 'from hello import main; main()')

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = ['hello.py', 'hello.pyc', 'sayhi',
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 8
Project: pyblish-win   Author: pyblish   File: dbtables.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __new_rowid(self, table, txn) :
        """Create a new unique row identifier"""
        unique = 0
        while not unique:
            # Generate a random 64-bit row ID string
            # (note: might have <64 bits of true randomness
            # but it's plenty for our database id needs!)
            blist = []
            for x in xrange(_rowid_str_len):
                blist.append(random.randint(0,255))
            newid = struct.pack('B'*_rowid_str_len, *blist)

            if sys.version_info[0] >= 3 :
                newid = newid.decode("iso8859-1")  # 8 bits

            # Guarantee uniqueness by adding this key to the database
            try:
                self.db.put(_rowid_key(table, newid), None, txn=txn,
                            flags=db.DB_NOOVERWRITE)
            except db.DBKeyExistError:
                pass
            else:
                unique = 1

        return newid 
Example 9
Project: pyblish-win   Author: pyblish   File: dbtables.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def Select(self, table, columns, conditions={}):
        """Select(table, columns, conditions) - retrieve specific row data
        Returns a list of row column->value mapping dictionaries.

        * columns - a list of which column data to return.  If
          columns is None, all columns will be returned.
        * conditions - a dictionary keyed on column names
          containing callable conditions expecting the data string as an
          argument and returning a boolean.
        """
        try:
            if not table in self.__tablecolumns:
                self.__load_column_info(table)
            if columns is None:
                columns = self.__tablecolumns[table]
            matching_rowids = self.__Select(table, columns, conditions)
        except db.DBError, dberror:
            if sys.version_info < (2, 6) :
                raise TableDBError, dberror[1]
            else :
                raise TableDBError, dberror.args[1]
        # return the matches as a list of dictionaries 
Example 10
Project: pyblish-win   Author: pyblish   File: dbshelve.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _extract(self, rec):
        if rec is None:
            return None
        else:
            key, data = rec
            # Safe in Python 2.x because expresion short circuit
            if sys.version_info[0] < 3 or isinstance(data, bytes) :
                return key, cPickle.loads(data)
            else :
                return key, cPickle.loads(bytes(data, "iso8859-1"))  # 8 bits

    #----------------------------------------------
    # Methods allowed to pass-through to self.dbc
    #
    # close, count, delete, get_recno, join_item


#--------------------------------------------------------------------------- 
Example 11
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        for i in xrange(5) :
            c = d.cursor()
            count = 0
            rec = c.first()
            while rec:
                count += 1
                key, data = rec
                self.assertEqual(self.makeData(key), data)
                rec = c.next()
            if verbose:
                print "%s: found %d records" % (name, count)
            c.close()

        if verbose:
            print "%s: thread finished" % name 
Example 12
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name
        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        count=len(keys)//len(readers)
        count2=count
        for x in keys :
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)

            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            count2-=1
            if not count2 :
                readers.pop().start()
                count2=count

        if verbose:
            print "%s: thread finished" % name 
Example 13
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        c = d.cursor()
        count = 0
        rec = dbutils.DeadlockWrap(c.first, max_retries=10)
        while rec:
            count += 1
            key, data = rec
            self.assertEqual(self.makeData(key), data)
            rec = dbutils.DeadlockWrap(c.next, max_retries=10)
        if verbose:
            print "%s: found %d records" % (name, count)
        c.close()

        if verbose:
            print "%s: thread finished" % name 
Example 14
Project: pyblish-win   Author: pyblish   File: test_compare.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def comparator_test_helper(self, comparator, expected_data) :
        data = expected_data[:]

        import sys
        if sys.version_info < (2, 6) :
            data.sort(cmp=comparator)
        else :  # Insertion Sort. Please, improve
            data2 = []
            for i in data :
                for j, k in enumerate(data2) :
                    r = comparator(k, i)
                    if r == 1 :
                        data2.insert(j, i)
                        break
                else :
                    data2.append(i)
            data = data2

        self.assertEqual(data, expected_data,
                         "comparator `%s' is not right: %s vs. %s"
                         % (comparator, expected_data, data)) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_compare.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None 
Example 16
Project: pyblish-win   Author: pyblish   File: test_compare.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def verifyStderr(self, method, successRe) :
        """
        Call method() while capturing sys.stderr output internally and
        call self.fail() if successRe.search() does not match the stderr
        output.  This is used to test for uncatchable exceptions.
        """
        stdErr = sys.stderr
        sys.stderr = StringIO()
        try:
            method()
        finally:
            temp = sys.stderr
            sys.stderr = stdErr
            errorOut = temp.getvalue()
            if not successRe.search(errorOut) :
                self.fail("unexpected stderr output:\n"+errorOut)
        if sys.version_info < (3, 0) :  # XXX: How to do this in Py3k ???
            sys.exc_traceback = sys.last_traceback = None 
Example 17
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: regression.py    Apache License 2.0 6 votes vote down vote up
def test_memory_consumption(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('simple_template.html', whiskey=42)

        def fire():
            with app.test_client() as c:
                rv = c.get('/')
                self.assert_equal(rv.status_code, 200)
                self.assert_equal(rv.data, b'<h1>42</h1>')

        # Trigger caches
        fire()

        # This test only works on CPython 2.7.
        if sys.version_info >= (2, 7) and \
                not hasattr(sys, 'pypy_translation_info'):
            with self.assert_no_leak():
                for x in range(10):
                    fire() 
Example 18
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: regression.py    Apache License 2.0 6 votes vote down vote up
def test_memory_consumption(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('simple_template.html', whiskey=42)

        def fire():
            with app.test_client() as c:
                rv = c.get('/')
                self.assert_equal(rv.status_code, 200)
                self.assert_equal(rv.data, b'<h1>42</h1>')

        # Trigger caches
        fire()

        # This test only works on CPython 2.7.
        if sys.version_info >= (2, 7) and \
                not hasattr(sys, 'pypy_translation_info'):
            with self.assert_no_leak():
                for x in range(10):
                    fire() 
Example 19
Project: sump2   Author: blackmesalabs   File: bd_server.py    GNU General Public License v3.0 6 votes vote down vote up
def wr( self, str ):
    if ( self.debug ):
      print("FT600_WR:" +  str );
    str = "~".join( str );# only using 8bits of 16bit FT600, so pad with ~
    bytes_to_write = len( str );# str is now "~1~2~3 .. ~e~f" - Twice as long
    channel = 0;
    result = False;
    timeout = 5;
    tx_pipe = 0x02 + channel;
    if sys.platform == 'linux2':
      tx_pipe -= 0x02;
    if ( sys.version_info.major == 3 ):
      str = str.encode('latin1');
    xferd = 0
    while ( xferd != bytes_to_write ):
      # write data to specified pipe
      xferd += self.D3XX.writePipe(tx_pipe,str,bytes_to_write-xferd);
    return; 
Example 20
Project: speedrun   Author: inferno-pytorch   File: setup.py    Apache License 2.0 6 votes vote down vote up
def binaries_directory():
    """Return the installation directory, or None"""
    if '--user' in sys.argv:
        paths = (site.getusersitepackages(),)
    else:
        py_version = '%s.%s' % (sys.version_info[0], sys.version_info[1])
        paths = (s % (py_version) for s in (
            sys.prefix + '/lib/python%s/site-packages/',
            sys.prefix + '/local/lib/python%s/site-packages/',
            sys.prefix + '/lib/python%s/dist-packages/',
            sys.prefix + '/local/lib/python%s/dist-packages/',
            '/Library/Python/%s/site-packages/',
        ))

    for path in paths:
        if os.path.exists(path):
            return path
    print('no installation path found', file=sys.stderr)
    return None 
Example 21
Project: twstock   Author: mlouielu   File: realtime.py    MIT License 6 votes vote down vote up
def get_raw(stocks) -> dict:
    req = requests.Session()
    req.get(SESSION_URL, proxies=get_proxies())

    r = req.get(
        STOCKINFO_URL.format(
            stock_id=_join_stock_id(stocks),
            time=int(time.time()) * 1000))

    if sys.version_info < (3, 5):
        try:
            return r.json()
        except ValueError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'}
    else:
        try:
            return r.json()
        except json.decoder.JSONDecodeError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'} 
Example 22
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def format_csv_value(cls, value):
        """Format value for rendering in CSV."""
        value = cls.format_value(value)
        if sys.version_info < (3, 0):
            return value.encode('utf-8')
        return value 
Example 23
Project: mutatest   Author: EvanKepner   File: transformers.py    MIT License 5 votes vote down vote up
def end_col_offset(self) -> Optional[int]:
        """End col offset: Python 3.8 will have this defined, in Python 3.7 it will be None."""
        ecol: Optional[int] = getattr(self.node, "end_col_offset", None)
        return ecol


####################################################################################################
# MUTATE AST Definitions
# Includes MutateBase and Mixins for 3.7 and 3.8 AST support
# MutateAST is constructed from Base + Mixins depending on sys.version_info
#################################################################################################### 
Example 24
Project: mutatest   Author: EvanKepner   File: test_api.py    MIT License 5 votes vote down vote up
def test_create_mutant_with_cache(binop_file, stdoutIO):
    """Change ast.Add to ast.Mult in a mutation including pycache changes."""
    genome = Genome(source_file=binop_file)

    # this target is the add_five() function, changing add to mult
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16

    target_idx = LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    mutation_op = ast.Mult

    mutant = genome.mutate(target_idx, mutation_op, write_cache=True)

    # uses the redirection for stdout to capture the value from the final output of binop_file
    with stdoutIO() as s:
        exec(mutant.mutant_code)
        assert int(s.getvalue()) == 25

    tag = sys.implementation.cache_tag
    expected_cfile = binop_file.parent / "__pycache__" / ".".join([binop_file.stem, tag, "pyc"])

    assert mutant.src_file == binop_file
    assert mutant.cfile == expected_cfile
    assert mutant.src_idx == target_idx 
Example 25
Project: mutatest   Author: EvanKepner   File: conftest.py    MIT License 5 votes vote down vote up
def boolop_expected_loc():
    """Expected location index of the boolop fixture"""
    # Py 3.7 vs 3.8
    end_lineno = None if sys.version_info < (3, 8) else 2
    end_col_offset = None if sys.version_info < (3, 8) else 18
    return LocIndex(
        ast_class="BoolOp",
        lineno=2,
        col_offset=11,
        op_type=ast.And,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
Example 26
Project: mutatest   Author: EvanKepner   File: conftest.py    MIT License 5 votes vote down vote up
def compare_expected_locs():
    """The compare expected locations based on the fixture"""
    # Py 3.7
    if sys.version_info < (3, 8):
        return [
            LocIndex(ast_class="Compare", lineno=2, col_offset=11, op_type=ast.Eq),
            LocIndex(ast_class="CompareIs", lineno=5, col_offset=11, op_type=ast.Is),
            LocIndex(ast_class="CompareIn", lineno=8, col_offset=11, op_type=ast.In),
        ]
    # Py 3.8
    return [
        LocIndex(
            ast_class="Compare",
            lineno=2,
            col_offset=11,
            op_type=ast.Eq,
            end_lineno=2,
            end_col_offset=17,
        ),
        LocIndex(
            ast_class="CompareIs",
            lineno=5,
            col_offset=11,
            op_type=ast.Is,
            end_lineno=5,
            end_col_offset=17,
        ),
        LocIndex(
            ast_class="CompareIn",
            lineno=8,
            col_offset=11,
            op_type=ast.In,
            end_lineno=8,
            end_col_offset=17,
        ),
    ]


####################################################################################################
# TRANSFORMERS: IF FIXTURES
#################################################################################################### 
Example 27
Project: mutatest   Author: EvanKepner   File: test_transformers.py    MIT License 5 votes vote down vote up
def test_MutateAST_visit_binop_37(binop_file):
    """Read only test to ensure locations are aggregated."""
    tree = Genome(binop_file).ast

    # Py 3.7 vs. Py 3.8
    end_lineno = None if sys.version_info < (3, 8) else 6
    end_col_offset = None if sys.version_info < (3, 8) else 17

    test_idx = LocIndex(
        ast_class="BinOp",
        lineno=6,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    test_mutation = ast.Pow

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=test_idx, mutation=test_mutation).visit(testing_tree)

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    # four locations from the binary operations in binop_file
    assert len(mast.locs) == 4

    # locs is an unordered set, cycle through to thd target and check the mutation
    for l in mast.locs:
        if (
            l.lineno == 6
            and l.col_offset == 11
            and l.end_lineno == end_lineno
            and l.end_col_offset == end_col_offset
        ):
            assert l.op_type == test_mutation 
Example 28
Project: mutatest   Author: EvanKepner   File: test_run.py    MIT License 5 votes vote down vote up
def binop_Add_LocIdx():
    """Binop Add LocIdx as a target for mutations."""
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16
    return LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
Example 29
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 30
Project: phrydy   Author: Josef-Friedrich   File: _version.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 31
Project: pyblish-win   Author: pyblish   File: dbapi.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def CheckExecuteDictMapping_Mapping(self):
        # Test only works with Python 2.5 or later
        if sys.version_info < (2, 5, 0):
            return

        class D(dict):
            def __missing__(self, key):
                return "foo"

        self.cu.execute("insert into test(name) values ('foo')")
        self.cu.execute("select name from test where name=:name", D())
        row = self.cu.fetchone()
        self.assertEqual(row[0], "foo") 
Example 32
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def net_if_addrs():
    """Return the addresses associated to each NIC (network interface
    card) installed on the system as a dictionary whose keys are the
    NIC names and value is a list of namedtuples for each address
    assigned to the NIC. Each namedtuple includes 4 fields:

     - family
     - address
     - netmask
     - broadcast

    'family' can be either socket.AF_INET, socket.AF_INET6 or
    psutil.AF_LINK, which refers to a MAC address.
    'address' is the primary address, 'netmask' and 'broadcast'
    may be None.
    Note: you can have more than one address of the same family
    associated with each interface.
    """
    has_enums = sys.version_info >= (3, 4)
    if has_enums:
        import socket
    rawlist = _psplatform.net_if_addrs()
    rawlist.sort(key=lambda x: x[1])  # sort by family
    ret = collections.defaultdict(list)
    for name, fam, addr, mask, broadcast in rawlist:
        if has_enums:
            try:
                fam = socket.AddressFamily(fam)
            except ValueError:
                if os.name == 'nt' and fam == -1:
                    fam = _psplatform.AF_LINK
                elif (hasattr(_psplatform, "AF_LINK") and
                        _psplatform.AF_LINK == fam):
                    # Linux defines AF_LINK as an alias for AF_PACKET.
                    # We re-set the family here so that repr(family)
                    # will show AF_LINK rather than AF_PACKET
                    fam = _psplatform.AF_LINK
        ret[name].append(_common.snic(fam, addr, mask, broadcast))
    return dict(ret) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_record_extensions(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(ext_modules=[
            Extension('xx', ['xxmodule.c'])])
        os.chdir(project_dir)
        support.copy_xxmodule_c(project_dir)

        buildextcmd = build_ext(dist)
        support.fixup_build_ext(buildextcmd)
        buildextcmd.ensure_finalized()

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        dist.command_obj['build_ext'] = buildextcmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = [_make_ext_name('xx'),
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 34
Project: pyblish-win   Author: pyblish   File: dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def associate(self, secondaryDB, callback, flags=0):
        def _shelf_callback(priKey, priData, realCallback=callback):
            # Safe in Python 2.x because expresion short circuit
            if sys.version_info[0] < 3 or isinstance(priData, bytes) :
                data = cPickle.loads(priData)
            else :
                data = cPickle.loads(bytes(priData, "iso8859-1"))  # 8 bits
            return realCallback(priKey, data)

        return self.db.associate(secondaryDB, _shelf_callback, flags)


    #def get(self, key, default=None, txn=None, flags=0): 
Example 35
Project: pyblish-win   Author: pyblish   File: test_basics.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test01_GetsAndPuts(self):
        d = self.d

        if verbose:
            print '\n', '-=' * 30
            print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__

        for key in ['0001', '0100', '0400', '0700', '0999']:
            data = d.get(key)
            if verbose:
                print data

        self.assertEqual(d.get('0321'), '0321-0321-0321-0321-0321')

        # By default non-existent keys return None...
        self.assertEqual(d.get('abcd'), None)

        # ...but they raise exceptions in other situations.  Call
        # set_get_returns_none() to change it.
        try:
            d.delete('abcd')
        except db.DBNotFoundError, val:
            if sys.version_info < (2, 6) :
                self.assertEqual(val[0], db.DB_NOTFOUND)
            else :
                self.assertEqual(val.args[0], db.DB_NOTFOUND)
            if verbose: print val 
Example 36
Project: pyblish-win   Author: pyblish   File: test_basics.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
        if verbose:
            print '\n', '-=' * 30
            print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
                  (self.__class__.__name__, get_raises_error, set_raises_error)

        if self.env and self.dbopenflags & db.DB_AUTO_COMMIT:
            txn = self.env.txn_begin()
        else:
            txn = None
        c = self.d.cursor(txn=txn)

        rec = c.first()
        count = 0
        while rec is not None:
            count = count + 1
            if verbose and count % 100 == 0:
                print rec
            try:
                rec = c.next()
            except db.DBNotFoundError, val:
                if get_raises_error:
                    if sys.version_info < (2, 6) :
                        self.assertEqual(val[0], db.DB_NOTFOUND)
                    else :
                        self.assertEqual(val.args[0], db.DB_NOTFOUND)
                    if verbose: print val
                    rec = None
                else:
                    self.fail("unexpected DBNotFoundError")
            self.assertEqual(c.get_current_size(), len(c.current()[1]),
                    "%s != len(%r)" % (c.get_current_size(), c.current()[1])) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        count=len(keys)//len(readers)
        count2=count
        for x in keys :
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)
            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            count2-=1
            if not count2 :
                readers.pop().start()
                count2=count

        if verbose:
            print "%s: finished creating records" % name

        if verbose:
            print "%s: thread finished" % name 
Example 38
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        count=len(keys)//len(readers)
        while len(keys):
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                keys2=keys[:count]
                for x in keys2 :
                    key = '%04d' % x
                    d.put(key, self.makeData(key), txn)
                    if verbose and x % 100 == 0:
                        print "%s: records %d - %d finished" % (name, start, x)
                txn.commit()
                keys=keys[count:]
                readers.pop().start()
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                txn.abort() 
Example 39
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        finished = False
        while not finished:
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                c = d.cursor(txn)
                count = 0
                rec = c.first()
                while rec:
                    count += 1
                    key, data = rec
                    self.assertEqual(self.makeData(key), data)
                    rec = c.next()
                if verbose: print "%s: found %d records" % (name, count)
                c.close()
                txn.commit()
                finished = True
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                c.close()
                txn.abort() 
Example 40
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if sys.version_info[0] >= 3 :
            from test_all import do_proxy_db_py3k
            self._flag_proxy_db_py3k = do_proxy_db_py3k(False)
        self.filename = get_new_database_path()
        self.do_open() 
Example 41
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        if sys.version_info[0] >= 3 :
            from test_all import do_proxy_db_py3k
            do_proxy_db_py3k(self._flag_proxy_db_py3k)
        self.do_close()
        test_support.unlink(self.filename) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mk(self, key):
        """Turn key into an appropriate key type for this db"""
        # override in child class for RECNO
        if sys.version_info[0] < 3 :
            return key
        else :
            return bytes(key, "iso8859-1")  # 8 bits 
Example 43
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def checkrec(self, key, value):
        # override this in a subclass if the key type is different

        if sys.version_info[0] >= 3 :
            if isinstance(key, bytes) :
                key = key.decode("iso8859-1")  # 8 bits

        x = key[1]
        if key[0] == 'S':
            self.assertEqual(type(value), str)
            self.assertEqual(value, 10 * x)

        elif key[0] == 'I':
            self.assertEqual(type(value), int)
            self.assertEqual(value, ord(x))

        elif key[0] == 'L':
            self.assertEqual(type(value), list)
            self.assertEqual(value, [x] * 10)

        elif key[0] == 'O':
            if sys.version_info[0] < 3 :
                from types import InstanceType
                self.assertEqual(type(value), InstanceType)
            else :
                self.assertEqual(type(value), DataClass)

            self.assertEqual(value.S, 10 * x)
            self.assertEqual(value.I, ord(x))
            self.assertEqual(value.L, [x] * 10)

        else:
            self.assertTrue(0, 'Unknown key type, fix the test')

#---------------------------------------------------------------------- 
Example 44
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        if sys.version_info[0] >= 3 :
            from test_all import do_proxy_db_py3k
            do_proxy_db_py3k(self._flag_proxy_db_py3k)
        self.do_close()
        test_support.rmtree(self.homeDir) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_dbtables.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        self.tdb.close()
        import sys
        if sys.version_info[0] >= 3 :
            from test_all import do_proxy_db_py3k
            do_proxy_db_py3k(self._flag_proxy_db_py3k)
        test_support.rmtree(self.testHomeDir) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_dbtables.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test01(self):
        tabname = "test01"
        colname = 'cool numbers'
        try:
            self.tdb.Drop(tabname)
        except dbtables.TableDBError:
            pass
        self.tdb.CreateTable(tabname, [colname])
        import sys
        if sys.version_info[0] < 3 :
            self.tdb.Insert(tabname, {colname: pickle.dumps(3.14159, 1)})
        else :
            self.tdb.Insert(tabname, {colname: pickle.dumps(3.14159,
                1).decode("iso8859-1")})  # 8 bits

        if verbose:
            self.tdb._db_print()

        values = self.tdb.Select(
            tabname, [colname], conditions={colname: None})

        import sys
        if sys.version_info[0] < 3 :
            colval = pickle.loads(values[0][colname])
        else :
            colval = pickle.loads(bytes(values[0][colname], "iso8859-1"))
        self.assertTrue(colval > 3.141)
        self.assertTrue(colval < 3.142) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_lock.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def theThread(self, lockType):
        import sys
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        if lockType ==  db.DB_LOCK_WRITE:
            lt = "write"
        else:
            lt = "read"

        anID = self.env.lock_id()
        if verbose:
            print "%s: locker ID: %s" % (name, anID)

        for i in xrange(1000) :
            lock = self.env.lock_get(anID, "some locked thing", lockType)
            if verbose:
                print "%s: Aquired %s lock: %s" % (name, lt, lock)

            self.env.lock_put(lock)
            if verbose:
                print "%s: Released %s lock: %s" % (name, lt, lock)

        self.env.lock_id_free(anID)


#---------------------------------------------------------------------- 
Example 48
Project: pyblish-win   Author: pyblish   File: test_recno.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test01_basic(self):
        d = db.DB()

        get_returns_none = d.set_get_returns_none(2)
        d.set_get_returns_none(get_returns_none)

        d.open(self.filename, db.DB_RECNO, db.DB_CREATE)

        for x in string.ascii_letters:
            recno = d.append(x * 60)
            self.assertIsInstance(recno, int)
            self.assertGreaterEqual(recno, 1)
            if verbose:
                print recno,

        if verbose: print

        stat = d.stat()
        if verbose:
            pprint(stat)

        for recno in range(1, len(d)+1):
            data = d[recno]
            if verbose:
                print data

            self.assertIsInstance(data, str)
            self.assertEqual(data, d.get(recno))

        try:
            data = d[0]  # This should raise a KeyError!?!?!
        except db.DBInvalidArgError, val:
            if sys.version_info < (2, 6) :
                self.assertEqual(val[0], db.EINVAL)
            else :
                self.assertEqual(val.args[0], db.EINVAL)
            if verbose: print val 
Example 49
Project: pyblish-win   Author: pyblish   File: test_cmd_line.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_version(self):
        version = 'Python %d.%d' % sys.version_info[:2]
        self.assertTrue(self.start_python('-V').startswith(version)) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_multiprocessing.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_task_done(self):
        queue = self.JoinableQueue()

        if sys.version_info < (2, 5) and not hasattr(queue, 'task_done'):
            self.skipTest("requires 'queue.task_done()' method")

        workers = [self.Process(target=self._test_task_done, args=(queue,))
                   for i in xrange(4)]

        for p in workers:
            p.daemon = True
            p.start()

        for i in xrange(10):
            queue.put(i)

        queue.join()

        for p in workers:
            queue.put(None)

        for p in workers:
            p.join()

#
#
#