backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / utils.py
1 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
2 # Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import importlib
18 import logging
19 import os
20 import sys
21
22 import six
23
24
25 LOG = logging.getLogger('ryu.utils')
26
27
28 def load_source(name, pathname):
29     """
30     This function provides the backward compatibility for 'imp.load_source'
31     in Python 2.
32
33     :param name: Name used to create or access a module object.
34     :param pathname: Path pointing to the source file.
35     :return: Loaded and initialized module.
36     """
37     if six.PY2:
38         import imp
39         return imp.load_source(name, pathname)
40     else:
41         loader = importlib.machinery.SourceFileLoader(name, pathname)
42         return loader.load_module(name)
43
44
45 def chop_py_suffix(p):
46     for suf in ['.py', '.pyc', '.pyo']:
47         if p.endswith(suf):
48             return p[:-len(suf)]
49     return p
50
51
52 def _likely_same(a, b):
53     try:
54         # Samefile not availible on windows
55         if sys.platform == 'win32':
56             if os.stat(a) == os.stat(b):
57                 return True
58         else:
59             if os.path.samefile(a, b):
60                 return True
61     except OSError:
62         # m.__file__ is not always accessible.  eg. egg
63         return False
64     if chop_py_suffix(a) == chop_py_suffix(b):
65         return True
66     return False
67
68
69 def _find_loaded_module(modpath):
70     # copy() to avoid RuntimeError: dictionary changed size during iteration
71     for k, m in sys.modules.copy().items():
72         if k == '__main__':
73             continue
74         if not hasattr(m, '__file__'):
75             continue
76         if _likely_same(m.__file__, modpath):
77             return m
78     return None
79
80
81 def _import_module_file(path):
82     abspath = os.path.abspath(path)
83     # Backup original sys.path before appending path to file
84     original_path = list(sys.path)
85     sys.path.append(os.path.dirname(abspath))
86     modname = chop_py_suffix(os.path.basename(abspath))
87     try:
88         return load_source(modname, abspath)
89     finally:
90         # Restore original sys.path
91         sys.path = original_path
92
93
94 def import_module(modname):
95     if os.path.exists(modname):
96         try:
97             # Try to import module since 'modname' is a valid path to a file
98             # e.g.) modname = './path/to/module/name.py'
99             return _import_module_file(modname)
100         except SyntaxError:
101             # The file didn't parse as valid Python code, try
102             # importing module assuming 'modname' is a Python module name
103             # e.g.) modname = 'path.to.module.name'
104             return importlib.import_module(modname)
105     else:
106         # Import module assuming 'modname' is a Python module name
107         # e.g.) modname = 'path.to.module.name'
108         return importlib.import_module(modname)
109
110
111 def round_up(x, y):
112     return ((x + y - 1) // y) * y
113
114
115 def hex_array(data):
116     """
117     Convert six.binary_type or bytearray into array of hexes to be printed.
118     """
119     # convert data into bytearray explicitly
120     return ' '.join('0x%02x' % byte for byte in bytearray(data))
121
122
123 def binary_str(data):
124     """
125     Convert six.binary_type or bytearray into str to be printed.
126     """
127     # convert data into bytearray explicitly
128     return ''.join('\\x%02x' % byte for byte in bytearray(data))