Here are the examples of the python api sys.version.replace taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
32 Examples
3
Example 1
Project: python-telegram-bot Source File: __main__.py
def print_ver_info():
print('python-telegram-bot {0}'.format(telegram_ver))
print('urllib3 {0}'.format(urllib3.__version__))
print('certifi {0}'.format(certifi.__version__))
print('future {0}'.format(future.__version__))
print('Python {0}'.format(sys.version.replace('\n', ' ')))
3
Example 2
Project: dnf-plugins-extras Source File: debug.py
def dump_system_info(self):
self.write("%%%%SYSTEM INFO\n")
uname = os.uname()
self.write(" uname: %s, %s\n" % (uname[2], uname[4]))
self.write(" rpm ver: %s\n" % rpm.__version__)
self.write(" python ver: %s\n" % sys.version.replace("\n", ""))
return
3
Example 3
Project: scrapy Source File: version.py
def run(self, args, opts):
if opts.verbose:
import lxml.etree
lxml_version = ".".join(map(str, lxml.etree.LXML_VERSION))
libxml2_version = ".".join(map(str, lxml.etree.LIBXML_VERSION))
print("Scrapy : %s" % scrapy.__version__)
print("lxml : %s" % lxml_version)
print("libxml2 : %s" % libxml2_version)
print("Twisted : %s" % twisted.version.short())
print("Python : %s" % sys.version.replace("\n", "- "))
print("pyOpenSSL : %s" % self._get_openssl_version())
print("Platform : %s" % platform.platform())
else:
print("Scrapy %s" % scrapy.__version__)
3
Example 4
Project: flent Source File: settings.py
def version(*args):
print("Flent v%s.\nRunning on Python %s." % (VERSION,
sys.version.replace("\n",
" ")))
try:
import matplotlib
import numpy
print("Using matplotlib version %s on numpy %s."
% (matplotlib.__version__, numpy.__version__))
except ImportError:
print("No matplotlib found. Plots won't be available.")
try:
from PyQt4 import QtCore
print("Using PyQt4 version %s" % QtCore.PYQT_VERSION_STR)
except ImportError:
print("No PyQt4. GUI won't work.")
sys.exit(0)
3
Example 5
def run():
"""
Runs the linter and tests
:return:
A bool - if the linter and tests ran successfully
"""
print('Python ' + sys.version.replace('\n', ''))
if sys.version_info >= (2, 7):
print('')
lint_result = run_lint()
else:
lint_result = True
print('\nRunning tests')
sys.stdout.flush()
tests_result = run_tests()
return lint_result and tests_result
3
Example 6
Project: pysql Source File: pysqlhelpers.py
def printComponentsVersion():
try:
pysqlVersion = currentVersion()
except PysqlException:
pysqlVersion = RED + BOLD + "missing" + RESET
try:
import cx_Oracle
cxVersion = cx_Oracle.version
except Exception:
cxVersion = RED + BOLD + "missing" + RESET
print(BOLD + "PySQL release: %s" % pysqlVersion + RESET)
print(" cx Oracle release: %s" % cxVersion)
print(" Python release: %s" % sys.version.replace("\n", " "))
3
Example 7
Project: evernote-sdk-python Source File: client.py
def _get_thrift_client(self, client_class, url):
http_client = THttpClient.THttpClient(url)
http_client.addHeaders(**{
'User-Agent': "%s / %s; Python / %s;"
% (self._user_agent_id, self._get_sdk_version(), sys.version.replace('\n',""))
})
thrift_protocol = TBinaryProtocol.TBinaryProtocol(http_client)
return client_class(thrift_protocol)
3
Example 8
Project: evernote-sdk-python3 Source File: client.py
def _get_thrift_client(self, client_class, url):
http_client = THttpClient.THttpClient(url)
http_client.setCustomHeaders({
'User-Agent': "%s / %s; Python / %s;"
% (
self._user_agent_id, self._get_sdk_version(), sys.version.replace("\n", ""))
})
thrift_protocol = TBinaryProtocol.TBinaryProtocol(http_client)
return client_class(thrift_protocol)
3
Example 9
Project: Piped Source File: scripts.py
def __call__(self, parser, namespace, values, option_string=None):
message = list()
message.append('piped (the Piped process daemon) %s, %s' % (piped.version, twisted.version))
message.append('')
message.append('Contrib packages:')
for name, version in sorted(self._find_plugin_versions().items()):
message.append('\t%s: %s' % (name, version))
message.append('')
message.append('Python version: %s' % sys.version.replace('\n', ''))
message.append('')
parser.exit(message=os.linesep.join(message))
3
Example 10
Project: robothon Source File: nosetester.py
def _show_system_info(self):
nose = import_nose()
import numpy
print "NumPy version %s" % numpy.__version__
npdir = os.path.dirname(numpy.__file__)
print "NumPy is installed in %s" % npdir
if 'scipy' in self.package_name:
import scipy
print "SciPy version %s" % scipy.__version__
spdir = os.path.dirname(scipy.__file__)
print "SciPy is installed in %s" % spdir
pyversion = sys.version.replace('\n','')
print "Python version %s" % pyversion
print "nose version %d.%d.%d" % nose.__versioninfo__
3
Example 11
Project: mythbox Source File: gtk2manhole.py
def _on_aboutMenuItem_activate(self, widget, *unused):
import sys
from os import path
self.output.append("""\
a Twisted Manhole client
Versions:
%(twistedVer)s
Python %(pythonVer)s on %(platform)s
GTK %(gtkVer)s / PyGTK %(pygtkVer)s
%(module)s %(modVer)s
http://twistedmatrix.com/
""" % {'twistedVer': copyright.longversion,
'pythonVer': sys.version.replace('\n', '\n '),
'platform': sys.platform,
'gtkVer': ".".join(map(str, gtk.gtk_version)),
'pygtkVer': ".".join(map(str, gtk.pygtk_version)),
'module': path.basename(__file__),
'modVer': __version__,
}, "local")
3
Example 12
Project: landlab Source File: nosetester.py
def show_system_info():
import landlab
import nose
print('landlab version %s' % landlab.__version__)
landlab_dir = os.path.dirname(landlab.__file__)
print('landlab is installed in %s' % landlab_dir)
print('Python version %s' % sys.version.replace('\n', ''))
print('nose version %d.%d.%d' % nose.__versioninfo__)
3
Example 13
Project: pyful Source File: __init__.py
def setup(self, rcpath):
error = self.loadrcfile(rcpath)
look.init_colors()
sysver = sys.version.replace(os.linesep, "")
widgets.message.puts("Launching on Python {0}".format(sysver))
if error:
widgets.message.exception(error)
widgets.message.error("RC error: instead loaded `{0}'".format(self.environs["RCFILE"]))
else:
widgets.message.puts("Loaded {0}".format(self.environs["RCFILE"]))
widget.refresh_all_widgets()
3
Example 14
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: nosetester.py
def _show_system_info(self):
nose = import_nose()
import numpy
print("NumPy version %s" % numpy.__version__)
relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
print("NumPy relaxed strides checking option:", relaxed_strides)
npdir = os.path.dirname(numpy.__file__)
print("NumPy is installed in %s" % npdir)
if 'scipy' in self.package_name:
import scipy
print("SciPy version %s" % scipy.__version__)
spdir = os.path.dirname(scipy.__file__)
print("SciPy is installed in %s" % spdir)
pyversion = sys.version.replace('\n', '')
print("Python version %s" % pyversion)
print("nose version %d.%d.%d" % nose.__versioninfo__)
3
Example 15
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: nosetester.py
def _show_system_info(self):
nose = import_nose()
import pandas
print("pandas version %s" % pandas.__version__)
import numpy
print("numpy version %s" % numpy.__version__)
pddir = os.path.dirname(pandas.__file__)
print("pandas is installed in %s" % pddir)
pyversion = sys.version.replace('\n', '')
print("Python version %s" % pyversion)
print("nose version %d.%d.%d" % nose.__versioninfo__)
3
Example 16
Project: simple-monitor-alert Source File: alerts.py
def test(self, section=None):
from simple_monitor_alert import __version__
from simple_monitor_alert.utils.system import get_hostname
for alert in self:
alert.send('[SMA] Check... Check... This is an alert notification',
'Congratulations! You are receiving this message because you have configured correctly '
'Simple Monitor Alert. Here you have some extra information.\n\n'
'- SMA version: {sma_version}\n'
'- Python version: {python_version}\n'
'- Hostname: {hostname}\n'
'- Send time: {dt}\n'
'- Alert section: {section}'.format(sma_version=__version__,
python_version=sys.version.replace('\n', ' '),
hostname=get_hostname(),
dt=datetime.datetime.now(),
section=alert.section))
3
Example 17
Project: nipy Source File: nosetester.py
def _show_system_info(self):
nose = import_nose()
import numpy
print("NumPy version %s" % numpy.__version__)
npdir = os.path.dirname(numpy.__file__)
print("NumPy is installed in %s" % npdir)
if 'scipy' in self.package_name:
import scipy
print("SciPy version %s" % scipy.__version__)
spdir = os.path.dirname(scipy.__file__)
print("SciPy is installed in %s" % spdir)
pyversion = sys.version.replace('\n','')
print("Python version %s" % pyversion)
print("nose version %d.%d.%d" % nose.__versioninfo__)
0
Example 18
Project: Limnoria Source File: plugin.py
@internationalizeDocstring
def version(self, irc, msg, args):
"""takes no arguments
Returns the version of the current bot.
"""
try:
newestUrl = 'https://api.github.com/repos/ProgVal/Limnoria/' + \
'commits/%s'
versions = {}
for branch in ('master', 'testing'):
data = json.loads(utils.web.getUrl(newestUrl % branch)
.decode('utf8'))
version = data['commit']['committer']['date']
# Strip the last 'Z':
version = version.rsplit('T', 1)[0].replace('-', '.')
if minisix.PY2 and isinstance(version, unicode):
version = version.encode('utf8')
versions[branch] = version
newest = _('The newest versions available online are %s.') % \
', '.join([_('%s (in %s)') % (y,x)
for x,y in versions.items()])
except utils.web.Error as e:
self.log.info('Couldn\'t get website version: %s', e)
newest = _('I couldn\'t fetch the newest version '
'from the Limnoria repository.')
s = _('The current (running) version of this Limnoria is %s, '
'running on Python %s. %s') % \
(conf.version, sys.version.replace('\n', ' '), newest)
irc.reply(s)
0
Example 19
Project: pyblosxom Source File: commandline.py
def test_installation(command, argv):
"""
This function gets called when someone starts up pyblosxom.cgi
from the command line with no REQUEST_METHOD environment variable.
It:
1. verifies config.py file properties
2. initializes all the plugins they have installed
3. runs ``cb_verify_installation``--plugins can print out whether
they are installed correctly (i.e. have valid config property
settings and can read/write to data files)
The goal is to be as useful and informative to the user as we can
be without being overly verbose and confusing.
This is designed to make it easier for a user to verify their
Pyblosxom installation is working and also to install new plugins
and verify that their configuration is correct.
"""
parser = build_parser("%prog test [options]")
parser.parse_args()
p = build_pyblosxom()
if not p:
return 0
request = p.get_request()
config = request.config
pwrap("System Information")
pwrap("==================")
pwrap("")
pwrap("- pyblosxom: %s" % __version__)
pwrap("- sys.version: %s" % sys.version.replace("\n", " "))
pwrap("- os.name: %s" % os.name)
codebase = os.path.dirname(os.path.dirname(__file__))
pwrap("- codebase: %s" % config.get("codebase", codebase))
pwrap("")
pwrap("Checking config.py file")
pwrap("=======================")
pwrap("- properties set: %s" % len(config))
config_keys = config.keys()
if "datadir" not in config_keys:
pwrap_error("- ERROR: 'datadir' must be set. Refer to installation "
"docuementation.")
elif not os.path.isdir(config["datadir"]):
pwrap_error("- ERROR: datadir '%s' does not exist."
" You need to create your datadir and give it "
" appropriate permissions." % config["datadir"])
else:
pwrap("- datadir '%s' exists." % config["datadir"])
if "flavourdir" not in config_keys:
pwrap("- WARNING: You should consider setting flavourdir and putting "
"your flavour templates there. See the docuementation for "
"more details.")
elif not os.path.isdir(config["flavourdir"]):
pwrap_error("- ERROR: flavourdir '%s' does not exist."
" You need to create your flavourdir and give it "
" appropriate permissions." % config["flavourdir"])
else:
pwrap("- flavourdir '%s' exists." % config["flavourdir"])
if (("blog_encoding" in config_keys
and config["blog_encoding"].lower() != "utf-8")):
pwrap_error("- WARNING: 'blog_encoding' is set to something other "
"than 'utf-8'. As of Pyblosxom 1.5, "
"this isn't a good idea unless you're absolutely certain "
"it's going to work for your blog.")
pwrap("")
pwrap("Checking plugin configuration")
pwrap("=============================")
import traceback
no_verification_support = []
if len(plugin_utils.plugins) + len(plugin_utils.bad_plugins) == 0:
pwrap(" - There are no plugins installed.")
else:
if len(plugin_utils.bad_plugins) > 0:
pwrap("- Some plugins failed to load.")
pwrap("")
pwrap("----")
for mem in plugin_utils.bad_plugins:
pwrap("plugin: %s" % mem[0])
print "%s" % mem[1]
pwrap("----")
pwrap_error("FAIL")
return(1)
if len(plugin_utils.plugins) > 0:
pwrap("- This goes through your plugins and asks each of them "
"to verify configuration and installation.")
pwrap("")
pwrap("----")
for mem in plugin_utils.plugins:
if hasattr(mem, "verify_installation"):
pwrap("plugin: %s" % mem.__name__)
print "file: %s" % mem.__file__
print "version: %s" % (str(getattr(mem, "__version__")))
try:
if mem.verify_installation(request) == 1:
pwrap("PASS")
else:
pwrap_error("FAIL")
except StandardError:
pwrap_error("FAIL: Exception thrown:")
traceback.print_exc(file=sys.stdout)
pwrap("----")
else:
mn = mem.__name__
mf = mem.__file__
no_verification_support.append( "'%s' (%s)" % (mn, mf))
if len(no_verification_support) > 0:
pwrap("")
pwrap("The following plugins do not support installation "
"verification:")
no_verification_support.sort()
for mem in no_verification_support:
print "- %s" % mem
pwrap("")
pwrap("Verification complete. Correct any errors and warnings above.")
0
Example 20
Project: pyg Source File: freeze.py
def site_info():
'''Return some site information'''
template = '''# Python version: {py_version!r}
# Python version info: {py_version_info!r}
# Python Prefix: {prefix!r}
# Platform: {platform!r}
# Pyg version: {pyg_version!r}
# Inside a virtualenv: {in_env}
# Site-Packages: {all_site!r}
# Bin: {bin!r}
'''
return template.format(
py_version=sys.version.replace('\n', ''),
py_version_info='.'.join(str(v) for v in sys.version_info),
platform=distutils.util.get_platform(),
prefix=sys.prefix,
pyg_version=__version__,
in_env=under_virtualenv(),
all_site=', '.join(ALL_SITE_PACKAGES),
bin=BIN
)
0
Example 21
Project: splash Source File: server.py
def log_splash_version():
import twisted
from twisted.python import log
from splash import lua
from splash.qtutils import get_versions
log.msg("Splash version: %s" % __version__)
verdict = get_versions()
versions = [
"Qt %s" % verdict['qt'],
"PyQt %s" % verdict['pyqt'],
"WebKit %s" % verdict['webkit'],
"sip %s" % verdict['sip'],
"Twisted %s" % twisted.version.short(),
]
if lua.is_supported():
versions.append(lua.get_version())
log.msg(", ".join(versions))
log.msg("Python %s" % sys.version.replace("\n", ""))
0
Example 22
Project: WAPT Source File: genpy.py
def do_gen_file_header(self):
la = self.typelib.GetLibAttr()
moduleDoc = self.typelib.GetDocuementation(-1)
docDesc = ""
if moduleDoc[1]:
docDesc = moduleDoc[1]
# Reset all the 'per file' state
self.bHaveWrittenDispatchBaseClass = 0
self.bHaveWrittenCoClassBaseClass = 0
self.bHaveWrittenEventBaseClass = 0
# You must provide a file correctly configured for writing unicode.
# We assert this is it may indicate somewhere in pywin32 that needs
# upgrading.
assert self.file.encoding, self.file
encoding = self.file.encoding # or "mbcs"
print >> self.file, '# -*- coding: %s -*-' % (encoding,)
print >> self.file, '# Created by makepy.py version %s' % (makepy_version,)
print >> self.file, '# By python version %s' % \
(sys.version.replace("\n", "-"),)
if self.sourceFilename:
print >> self.file, "# From type library '%s'" % (os.path.split(self.sourceFilename)[1],)
print >> self.file, '# On %s' % time.ctime(time.time())
print >> self.file, build._makeDocString(docDesc)
print >> self.file, 'makepy_version =', repr(makepy_version)
print >> self.file, 'python_version = 0x%x' % (sys.hexversion,)
print >> self.file
print >> self.file, 'import win32com.client.CLSIDToClass, pythoncom, pywintypes'
print >> self.file, 'import win32com.client.util'
print >> self.file, 'from pywintypes import IID'
print >> self.file, 'from win32com.client import Dispatch'
print >> self.file
print >> self.file, '# The following 3 lines may need tweaking for the particular server'
print >> self.file, '# Candidates are pythoncom.Missing, .Empty and .ArgNotFound'
print >> self.file, 'defaultNamedOptArg=pythoncom.Empty'
print >> self.file, 'defaultNamedNotOptArg=pythoncom.Empty'
print >> self.file, 'defaultUnnamedArg=pythoncom.Empty'
print >> self.file
print >> self.file, 'CLSID = ' + repr(la[0])
print >> self.file, 'MajorVersion = ' + str(la[3])
print >> self.file, 'MinorVersion = ' + str(la[4])
print >> self.file, 'LibraryFlags = ' + str(la[5])
print >> self.file, 'LCID = ' + hex(la[1])
print >> self.file
0
Example 23
def do_gen_file_header(self):
la = self.typelib.GetLibAttr()
moduleDoc = self.typelib.GetDocuementation(-1)
docDesc = ""
if moduleDoc[1]:
docDesc = moduleDoc[1]
# Reset all the 'per file' state
self.bHaveWrittenDispatchBaseClass = 0
self.bHaveWrittenCoClassBaseClass = 0
self.bHaveWrittenEventBaseClass = 0
# You must provide a file correctly configured for writing unicode.
# We assert this is it may indicate somewhere in pywin32 that needs
# upgrading.
assert self.file.encoding, self.file
encoding = self.file.encoding # or "mbcs"
print('# -*- coding: %s -*-' % (encoding,), file=self.file)
print('# Created by makepy.py version %s' % (makepy_version,), file=self.file)
print('# By python version %s' % \
(sys.version.replace("\n", "-"),), file=self.file)
if self.sourceFilename:
print("# From type library '%s'" % (os.path.split(self.sourceFilename)[1],), file=self.file)
print('# On %s' % time.ctime(time.time()), file=self.file)
print(build._makeDocString(docDesc), file=self.file)
print('makepy_version =', repr(makepy_version), file=self.file)
print('python_version = 0x%x' % (sys.hexversion,), file=self.file)
print(file=self.file)
print('import win32com.client.CLSIDToClass, pythoncom, pywintypes', file=self.file)
print('import win32com.client.util', file=self.file)
print('from pywintypes import IID', file=self.file)
print('from win32com.client import Dispatch', file=self.file)
print(file=self.file)
print('# The following 3 lines may need tweaking for the particular server', file=self.file)
print('# Candidates are pythoncom.Missing, .Empty and .ArgNotFound', file=self.file)
print('defaultNamedOptArg=pythoncom.Empty', file=self.file)
print('defaultNamedNotOptArg=pythoncom.Empty', file=self.file)
print('defaultUnnamedArg=pythoncom.Empty', file=self.file)
print(file=self.file)
print('CLSID = ' + repr(la[0]), file=self.file)
print('MajorVersion = ' + str(la[3]), file=self.file)
print('MinorVersion = ' + str(la[4]), file=self.file)
print('LibraryFlags = ' + str(la[5]), file=self.file)
print('LCID = ' + hex(la[1]), file=self.file)
print(file=self.file)
0
Example 24
@memoize
def environment_info(self):
"""
Return a dictionary representing the server environment.
The idea is that the result of this function will rarely (if ever)
change for a given app instance. Ergo, the result can be cached between
requests.
"""
return {
"application_environment": {
"framework": "django",
"env": dict(os.environ),
"language": "python",
"language_version": sys.version.replace('\n', ''),
"application_root_directory": self.project_root()
},
"client": {
"name": "django-exceptional",
"version": __version__,
"protocol_version": EXCEPTIONAL_PROTOCOL_VERSION
}
}
0
Example 25
def run(self, test_args=None):
args = self.parse_args(test_args)
log.level = args.log_level
log.debug(sys.version.replace("\n", ""))
if args.module_name is None:
self.print_help()
self.exit()
if args.module_name == "secret" or (args.module_name == "config" and args.init):
args.run(args)
return
try:
with Config(conf=args.conf, key_file=args.key) as config:
colorful = config.get_value("colorful", default=True)
if not colorful:
colors.is_colorful = False
args.run(args)
except ConfigNotFound as error:
log.debug(error)
if args.conf is None:
args.conf = home_file(".girafferc")
if prompt_bool(("Configuration file '{}' not found, would you like to create one now "
"using the default template?").format(args.conf), default=True):
result = Config.write_default(args.conf)
if result:
log.write(colors.green(result))
log.write(MESSAGE_WRITE_DEFAULT.format(args.conf))
self.run()
else:
log.write(colors.fail("Was not successful"))
except KeyNotFound as error:
log.debug(error)
if args.key is None:
args.key = home_file(".giraffepg")
if prompt_bool("Key file '{}' not found, would you like to create one now?".format(args.key),
default=True):
create_key_file(args.key)
log.write("Key file '{}' created successfully.".format(args.key))
self.run()
else:
raise error
except InvalidCredentialsError as error:
if args.protect:
Config.lock_connection(args.conf, args.dsn)
raise error
0
Example 26
Project: autobahn-testsuite Source File: util.py
def envinfo():
res = {}
res['platform'] = {'hostname': platform.node(),
'os': platform.platform()}
res['python'] = {'version': platform.python_version(),
'implementation': platform.python_implementation(),
'versionVerbose': sys.version.replace('\n', ' ')}
res['twisted'] = {'version': None, 'reactor': None}
try:
import pkg_resources
res['twisted']['version'] = pkg_resources.require("Twisted")[0].version
except:
## i.e. no setuptools installed ..
pass
try:
from twisted.internet import reactor
res['twisted']['reactor'] = str(reactor.__class__.__name__)
except:
pass
v1 = str(Utf8Validator)
v1 = v1[v1.find("'")+1:-2]
v2 = str(XorMaskerNull)
v2 = v2[v2.find("'")+1:-2]
res['autobahn'] = {'version': autobahn.version,
'utf8Validator': v1,
'xorMasker': v2,
'jsonProcessor': '%s-%s' % (autobahn.wamp.json_lib.__name__, autobahn.wamp.json_lib.__version__)}
res['autobahntestsuite'] = {'version': autobahntestsuite.version}
return res
0
Example 27
Project: changes Source File: auth.py
def get_auth_flow(redirect_uri=None, state=""):
# XXX(dcramer): we have to generate this each request because oauth2client
# doesn't want you to set redirect_uri as part of the request, which causes
# a lot of runtime issues.
auth_uri = GOOGLE_AUTH_URI
if current_app.config['GOOGLE_DOMAIN']:
auth_uri = auth_uri + '?hd=' + current_app.config['GOOGLE_DOMAIN']
return OAuth2WebServerFlow(
client_id=current_app.config['GOOGLE_CLIENT_ID'],
client_secret=current_app.config['GOOGLE_CLIENT_SECRET'],
scope='email',
redirect_uri=redirect_uri,
user_agent='changes/{0} (python {1})'.format(
changes.VERSION,
# Newer versions of Python stdlib disallow newlines in header values.
# See http://bugs.python.org/issue22928
sys.version.replace('\n', ' -- '),
),
auth_uri=auth_uri,
token_uri=GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI,
state=state,
approval_prompt='force',
access_type='offline'
)
0
Example 28
Project: flask-exceptional Source File: flask_exceptional.py
@staticmethod
def __get_application_data(app):
"""Get application data.
"""
environment = {}
for name in app.config:
value = app.config[name]
environment[name] = str(value) if value else None
for name in os.environ:
value = os.environ[name]
environment["os.%s" % name] = str(value)
if pkg_resources:
modules = {}
for module in pkg_resources.working_set:
modules[module.project_name] = module.version
else:
modules = None
return {
"framework": "flask",
"env": Exceptional.__filter(app, environment,
"EXCEPTIONAL_ENVIRONMENT_FILTER"),
"language": "python",
"language_version": sys.version.replace('\n', ''),
"application_root_directory": app.root_path,
"loaded_libraries": modules
}
0
Example 29
Project: xbmc-addon-abc-iview Source File: issue_reporter.py
def format_issue(issue_data):
"""
Build our formatted GitHub issue string
"""
# os.uname() is not available on Windows, so we make this optional.
try:
uname = os.uname()
os_string = ' (%s %s %s)' % (uname[0], uname[2], uname[4])
except AttributeError:
os_string = ''
content = [
"*Automatic bug report from end-user.*\n## Environment\n"
"**Plugin Name:** %s" % config.NAME,
"**Plugin ID:** %s" % config.ADDON_ID,
"**Plugin Version:** %s" % config.VERSION,
"**XBMC/Kodi Version:** %s" % get_xbmc_version(),
"**Python Version:** %s" % sys.version.replace('\n', ''),
"**Operating System:** [%s] %s" % (sys.platform, os_string),
"**IP Address:** %s" % get_public_ip(),
"**ISP :** %s" % get_isp(),
"**Python Path:**\n```\n%s\n```" % '\n'.join(sys.path),
"\n## Traceback\n```\n%s\n```" % issue_data,
]
log_url = upload_log()
if log_url:
content.append("\n[Full xbmc.log](%s)" % log_url)
return "\n".join(content)
0
Example 30
def run(self):
"""
Runs all the jobs jobs.
Returns:
All errors encountered as a list of list.
[[error_dicts for job 1], [error_dicts for job 2], ....]
"""
cwd = os.getcwd()
with ScratchDir(self.scratch_dir, create_symbolic_link=True,
copy_to_current_on_exit=True,
copy_from_current_on_enter=True) as temp_dir:
self.total_errors = 0
start = datetime.datetime.now()
logger.info("Run started at {} in {}.".format(
start, temp_dir))
v = sys.version.replace("\n", " ")
logger.info("Custodian running on Python version {}".format(v))
logger.info("Hostname: {}, Cluster: {}".format(*get_execution_host_info()))
try:
# skip jobs until the restart
for job_n, job in islice(enumerate(self.jobs, 1),
self.restart, None):
self._run_job(job_n, job)
# Checkpoint after each job so that we can recover from last
# point and remove old checkpoints
if self.checkpoint:
self.restart = job_n
Custodian._save_checkpoint(cwd, job_n)
except CustodianError as ex:
logger.error(ex.message)
if ex.raises:
raise RuntimeError("{} errors reached: {}. Exited..."
.format(self.total_errors, ex))
finally:
# Log the corrections to a json file.
logger.info("Logging to {}...".format(Custodian.LOG_FILE))
dumpfn(self.run_log, Custodian.LOG_FILE, cls=MontyEncoder,
indent=4)
end = datetime.datetime.now()
logger.info("Run ended at {}.".format(end))
run_time = end - start
logger.info("Run completed. Total time taken = {}."
.format(run_time))
if self.gzipped_output:
gzip_dir(".")
# Cleanup checkpoint files (if any) if run is successful.
Custodian._delete_checkpoints(cwd)
return self.run_log
0
Example 31
Project: custodian Source File: custodian.py
def run_interrupted(self):
"""
Runs custodian in a interuppted mode, which sets up and
validates jobs but doesn't run the executable
Returns:
number of remaining jobs
Raises:
CustodianError on unrecoverable errors, and jobs that fail
validation
"""
try:
cwd = os.getcwd()
start = datetime.datetime.now()
v = sys.version.replace("\n", " ")
logger.info("Custodian started in singleshot mode at {} in {}."
.format(start, cwd))
logger.info("Custodian running on Python version {}".format(v))
# load run log
if os.path.exists(Custodian.LOG_FILE):
self.run_log = loadfn(Custodian.LOG_FILE, cls=MontyDecoder)
if len(self.run_log) == 0:
# starting up an initial job - setup input and quit
job_n = 0
job = self.jobs[job_n]
logger.info("Setting up job no. 1 ({}) ".format(job.name))
job.setup()
self.run_log.append({"job": job.as_dict(), "corrections": [], 'job_n': job_n})
return len(self.jobs)
else:
# Continuing after running calculation
job_n = self.run_log[-1]['job_n']
job = self.jobs[job_n]
# If we had to fix errors from a previous run, insert clean log
# dict
if len(self.run_log[-1]['corrections']) > 0:
logger.info("Reran {}.run due to fixable errors".format(job.name))
# check error handlers
logger.info("Checking error handlers for {}.run".format(job.name))
if self._do_check(self.handlers):
logger.info("Failed validation based on error handlers")
# raise an error for an unrecoverable error
for x in self.run_log[-1]["corrections"]:
if not x["actions"] and x["handler"].raises_runtime_error:
s = "Unrecoverable error for handler: {}. " \
"Raising RuntimeError".format(x["handler"])
raise CustodianError(s, True, x["handler"])
logger.info("Corrected input based on error handlers")
# Return with more jobs to run if recoverable error caught
# and corrected for
return len(self.jobs) - job_n
# check validators
logger.info("Checking validator for {}.run".format(job.name))
for v in self.validators:
if v.check():
logger.info("Failed validation based on validator")
s = "Validation failed: {}".format(v)
raise CustodianError(s, True, v)
logger.info("Postprocessing for {}.run".format(job.name))
job.postprocess()
# IF DONE WITH ALL JOBS - DELETE ALL CHECKPOINTS AND RETURN
# VALIDATED
if len(self.jobs) == (job_n + 1):
self.finished = True
return 0
# Setup next job_n
job_n += 1
job = self.jobs[job_n]
self.run_log.append({"job": job.as_dict(), "corrections": [],
'job_n': job_n})
job.setup()
return len(self.jobs) - job_n
except CustodianError as ex:
logger.error(ex.message)
if ex.raises:
raise RuntimeError("{} errors reached: {}. Exited..."
.format(self.total_errors, ex))
finally:
#Log the corrections to a json file.
logger.info("Logging to {}...".format(Custodian.LOG_FILE))
dumpfn(self.run_log, Custodian.LOG_FILE, cls=MontyEncoder,
indent=4)
end = datetime.datetime.now()
logger.info("Run ended at {}.".format(end))
run_time = end - start
logger.info("Run completed. Total time taken = {}."
.format(run_time))
if self.finished and self.gzipped_output:
gzip_dir(".")
0
Example 32
Project: coveragepy Source File: control.py
def sys_info(self):
"""Return a list of (key, value) pairs showing internal information."""
import coverage as covmod
self._init()
ft_plugins = []
for ft in self.plugins.file_tracers:
ft_name = ft._coverage_plugin_name
if not ft._coverage_enabled:
ft_name += " (disabled)"
ft_plugins.append(ft_name)
info = [
('version', covmod.__version__),
('coverage', covmod.__file__),
('cover_dirs', self.cover_dirs),
('pylib_dirs', self.pylib_dirs),
('tracer', self.collector.tracer_name()),
('plugins.file_tracers', ft_plugins),
('config_files', self.config.attempted_config_files),
('configs_read', self.config.config_files),
('data_path', self.data_files.filename),
('python', sys.version.replace('\n', '')),
('platform', platform.platform()),
('implementation', platform.python_implementation()),
('executable', sys.executable),
('cwd', os.getcwd()),
('path', sys.path),
('environment', sorted(
("%s = %s" % (k, v))
for k, v in iitems(os.environ)
if k.startswith(("COV", "PY"))
)),
('command_line', " ".join(getattr(sys, 'argv', ['???']))),
]
matcher_names = [
'source_match', 'source_pkgs_match',
'include_match', 'omit_match',
'cover_match', 'pylib_match',
]
for matcher_name in matcher_names:
matcher = getattr(self, matcher_name)
if matcher:
matcher_info = matcher.info()
else:
matcher_info = '-none-'
info.append((matcher_name, matcher_info))
return info