def get_version():
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
file_dir = os.path.realpath(os.path.dirname(__file__))
with open(
os.path.join(file_dir, '..', 'behold', 'version.py')) as f:
txt = f.read()
version_match = re.search(
r"""^__version__ = ['"]([^'"]*)['"]""", txt, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
python类M的实例源码
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings
doc = CutCommonSpacePrefix(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space
# 1) keep double new lines
# 2) keep ws after new lines if not empty line
# 3) all other new lines shall be changed to a space
# Solution: Match new lines between non white space and replace with space.
doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M)
return doc
def is_module_loaded(module):
"""Checks if a kernel module is already loaded"""
matches = re.findall('^%s[ ]+' % module, lsmod(), re.M)
return len(matches) > 0
def is_enabled():
"""
Check if `ufw` is enabled
:returns: True if ufw is enabled
"""
output = subprocess.check_output(['ufw', 'status'],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
m = re.findall(r'^Status: active\n', output, re.M)
return len(m) >= 1
def enable(soft_fail=False):
"""
Enable ufw
:param soft_fail: If set to True silently disables IPv6 support in ufw,
otherwise a UFWIPv6Error exception is raised when IP6
support is broken.
:returns: True if ufw is successfully enabled
"""
if is_enabled():
return True
if not is_ipv6_ok(soft_fail):
disable_ipv6()
output = subprocess.check_output(['ufw', 'enable'],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
m = re.findall('^Firewall is active and enabled on system startup\n',
output, re.M)
hookenv.log(output, level='DEBUG')
if len(m) == 0:
hookenv.log("ufw couldn't be enabled", level='WARN')
return False
else:
hookenv.log("ufw enabled", level='INFO')
return True
def disable():
"""
Disable ufw
:returns: True if ufw is successfully disabled
"""
if not is_enabled():
return True
output = subprocess.check_output(['ufw', 'disable'],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
m = re.findall(r'^Firewall stopped and disabled on system startup\n',
output, re.M)
hookenv.log(output, level='DEBUG')
if len(m) == 0:
hookenv.log("ufw couldn't be disabled", level='WARN')
return False
else:
hookenv.log("ufw disabled", level='INFO')
return True
def default_policy(policy='deny', direction='incoming'):
"""
Changes the default policy for traffic `direction`
:param policy: allow, deny or reject
:param direction: traffic direction, possible values: incoming, outgoing,
routed
"""
if policy not in ['allow', 'deny', 'reject']:
raise UFWError(('Unknown policy %s, valid values: '
'allow, deny, reject') % policy)
if direction not in ['incoming', 'outgoing', 'routed']:
raise UFWError(('Unknown direction %s, valid values: '
'incoming, outgoing, routed') % direction)
output = subprocess.check_output(['ufw', 'default', policy, direction],
universal_newlines=True,
env={'LANG': 'en_US',
'PATH': os.environ['PATH']})
hookenv.log(output, level='DEBUG')
m = re.findall("^Default %s policy changed to '%s'\n" % (direction,
policy),
output, re.M)
if len(m) == 0:
hookenv.log("ufw couldn't change the default policy to %s for %s"
% (policy, direction), level='WARN')
return False
else:
hookenv.log("ufw default policy for %s changed to %s"
% (direction, policy), level='INFO')
return True
def defSyntax(self):
'''Define re patterns according to syntax.'''
#------------------REGEX patterns------------------
if self.syntax=='markdown':
self._img_re=re.compile('^(.*)!\\[(.+?)\\]\\((.+?)\\)', re.M | re.L)
self._h_re_base = r'''
(^(.+)[ \t]*\n(=+|-+)[ \t]*\n+)
|
(^(\#{%s}) # \1 = string of #'s
[ \t]*
(.+?) # \2 = Header text
[ \t]*
(?<!\\) # ensure not an escaped trailing '#'
\#* # optional closing #'s (not counted)
\n+
)
'''
self._all_h_re=re.compile(self._h_re_base %'1,6', re.X | re.M)
elif self.syntax=='zim':
self._img_re=re.compile('^(.*)\\{\\{(.+?)\\}\\}(.*)$', re.M | re.L)
self._h_re_base = r'''
^(\={%s}) # \1 = string of ='s
[ \t]*
(.+?) # \2 = Header text
[ \t]*
\1
\n+
'''
self._all_h_re=re.compile(self._h_re_base %'1,6', re.X | re.M)
else:
raise Exception("Unknown syntax %s" %self.syntax)
return
def createNoteBook(title,geeknote=None,verbose=True):
#-------------------Trunc title-------------------
title=title.strip()
title=truncStr(title,MAX_NOTEBOOK_TITLE_LEN)
#-------Make sure title doesnt start with #-------
tp=textparse.TextParser('markdown')
_h_re=re.compile(tp._h_re_base %'1,', re.X | re.M)
m=_h_re.match(title)
if m:
title=m.group(6)
#---------------------Connect---------------------
if geeknote is None:
geeknote=GeekNoteConnector()
geeknote.connectToEvertone()
#-----------------Check if exists-----------------
notebooks=geeknote.getEvernote().findNotebooks()
out.preloader.stop()
if not isinstance(title,unicode):
title=unicode(title,'utf8')
notebooks=[unicode(ii.name,'utf8') for ii in notebooks]
if title in notebooks:
out.successMessage('Notebook already exists.')
return 0
else:
out.preloader.setMessage("Creating notebook...")
result = geeknote.getEvernote().createNotebook(name=title)
if result:
out.successMessage("Notebook has been successfully created.")
return 0
else:
out.failureMessage("Error while the process "
"of creating the notebook.")
return tools.exitErr()
def createNote(title,content,tags,notebook,geeknote=None,\
skipnotebook=False):
#-------------------Trunc texts-------------------
notebook=notebook.strip()
notebook=truncStr(notebook,MAX_NOTEBOOK_TITLE_LEN)
title=title.strip()
title=truncStr(title,MAX_NOTE_TITLE_LEN)
#-------Make sure title doesnt start with #-------
tp=textparse.TextParser('markdown')
_h_re=re.compile(tp._h_re_base %'1,', re.X | re.M)
m=_h_re.match(title)
if m:
title=m.group(6)
m=_h_re.match(notebook)
if m:
notebook=m.group(6)
if tags is not None and len(tags.split(','))>=MAX_NOTE_TAGS:
tags=u','.join(tags.split(',')[:MAX_NOTE_TAGS])
#---------------------Connect---------------------
if geeknote is None:
geeknote=GeekNoteConnector()
geeknote.connectToEvertone()
#-----------------Create notebook-----------------
if not skipnotebook:
result=createNoteBook(notebook,geeknote)
if skipnotebook or result==0:
#----------------------Write----------------------
inputdata=geeknote._parseInput(title,content,tags,notebook,None)
out.preloader.setMessage('Creating note...')
result=bool(geeknote.getEvernote().createNote(**inputdata))
if result:
out.successMessage("Note has been successfully saved.")
else:
out.failureMessage("Error while saving the note.")
def _dict(self):
"""
Construct an ordered dict from the naming elements of the path
"""
d = OrderedDict()
for json_fragment in re.findall('\((.*?)\)', self, re.M):
json_ordered_dict = json.loads(re.sub("'", '"', json_fragment),
object_pairs_hook=OrderedDict)
d.update(json_ordered_dict)
return d
def get_version(*file_paths):
"""Retrieves the version from tigerleaflet/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
def find_meta(meta):
"""
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta),
META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
def handle_command(self):
try:
s = re.search(r'.* -name (.*)$|\s.*', self.cmd_str, re.M|re.I)
return {
"name": s.group(1)
}
except:
return {}
def get_version(*file_paths):
"""Retrieves the version from magic_cards/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
def get_version(*file_paths):
"""
Extract the version string from the file at the given relative path fragments.
"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read() # pylint: disable=open-builtin
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
def get_version(*file_paths):
"""
Extract the version string from the file at the given relative path fragments.
"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
def read_version():
with open(os.path.join(os.path.dirname(__file__), 'pyplanet', '__init__.py')) as handler:
return re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", handler.read(), re.M).group(1)
def is_module_loaded(module):
"""Checks if a kernel module is already loaded"""
matches = re.findall('^%s[ ]+' % module, lsmod(), re.M)
return len(matches) > 0