本文整理汇总了Python中rhn.i18n.sstr函数的典型用法代码示例。如果您正苦于以下问题:Python sstr函数的具体用法?Python sstr怎么用?Python sstr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sstr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: save
def save(self):
if self.fileName == None:
return
# this really shouldn't happen, since it means that the
# /etc/sysconfig/rhn directory doesn't exist, which is way broken
# and note the attempted fix breaks useage of this by the applet
# since it reuses this code to create its config file, and therefore
# tries to makedirs() the users home dir again (with a specific perms)
# and fails (see #130391)
if not os.access(self.fileName, os.R_OK):
if not os.access(os.path.dirname(self.fileName), os.R_OK):
print(_("%s was not found" % os.path.dirname(self.fileName)))
return
f = open(self.fileName+'.new', "w")
os.chmod(self.fileName, int('0600', 8))
f.write("# Automatically generated Red Hat Update Agent "\
"config file, do not edit.\n")
f.write("# Format: 1.0\n")
f.write("")
for key in self.dict.keys():
(comment, value) = self.dict[key]
f.write(sstr(u"%s[comment]=%s\n" % (key, comment)))
if type(value) != type([]):
value = [ value ]
if key in FileOptions:
value = map(os.path.abspath, value)
f.write(sstr(u"%s=%s\n" % (key, ';'.join(map(str, value)))))
f.write("\n")
f.close()
os.rename(self.fileName+'.new', self.fileName)
开发者ID:TJM,项目名称:spacewalk,代码行数:34,代码来源:config.py
示例2: __init__
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(self.screen, sstr(WHY_REGISTER_WINDOW),
1, 2)
why_register_text = WHY_REGISTER_TEXT + "\n\n" + \
WHY_REGISTER_SEC + "\n" + \
WHY_REGISTER_SEC_TXT + "\n\n" + \
WHY_REGISTER_DLD + "\n" + \
WHY_REGISTER_DLD_TXT + "\n\n" + \
WHY_REGISTER_SUPP + "\n" + \
WHY_REGISTER_SUPP_TXT + "\n\n" + \
WHY_REGISTER_COMP + "\n" + \
WHY_REGISTER_COMP_TXT + "\n\n" + \
WHY_REGISTER_TIP
tb = snack.Textbox(size[0]-10, size[1]-14, sstr(why_register_text), 1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.bb = snack.ButtonBar(self.screen,
[(sstr(BACK_REGISTER), "back")])
toplevel.add(self.bb, 0, 1, growx = 1)
self.g = toplevel
开发者ID:jdobes,项目名称:spacewalk,代码行数:29,代码来源:tui.py
示例3: _processFile
def _processFile(filename, relativeDir=None, source=None, nosig=None):
""" Processes a file
Returns a hash containing:
header
packageSize
checksum
relativePath
nvrea
"""
# Is this a file?
if not os.access(filename, os.R_OK):
raise UploadError("Could not stat the file %s" % filename)
if not os.path.isfile(filename):
raise UploadError("%s is not a file" % filename)
# Size
size = os.path.getsize(filename)
try:
a_pkg = package_from_filename(filename)
a_pkg.read_header()
a_pkg.payload_checksum()
assert a_pkg.header
except:
raise_with_tb(UploadError("%s is not a valid package" % filename), sys.exc_info()[2])
if nosig is None and not a_pkg.header.is_signed():
raise UploadError("ERROR: %s: unsigned rpm (use --nosig to force)"
% filename)
# Get the name, version, release, epoch, arch
lh = []
for k in ['name', 'version', 'release', 'epoch']:
if k == 'epoch' and not a_pkg.header[k]:
# Fix the epoch
lh.append(sstr(""))
else:
lh.append(sstr(a_pkg.header[k]))
if source:
lh.append('src')
else:
lh.append(sstr(a_pkg.header['arch']))
# Build the header hash to be sent
info = {'header': Binary(a_pkg.header.unload()),
'checksum_type': a_pkg.checksum_type,
'checksum': a_pkg.checksum,
'packageSize': size,
'header_start': a_pkg.header_start,
'header_end': a_pkg.header_end}
if relativeDir:
# Append the relative dir too
info["relativePath"] = "%s/%s" % (relativeDir,
os.path.basename(filename))
info['nvrea'] = tuple(lh)
return info
开发者ID:hlawatschek,项目名称:spacewalk,代码行数:58,代码来源:uploadLib.py
示例4: _getOSVersionAndRelease
def _getOSVersionAndRelease():
ts = transaction.initReadOnlyTransaction()
for h in ts.dbMatch('Providename', "oraclelinux-release"):
SYSRELVER = 'system-release(releasever)'
version = sstr(h['version'])
release = sstr(h['release'])
if SYSRELVER in h['providename']:
provides = dict(zip(h['providename'], h['provideversion']))
release = '%s-%s' % (version, release)
version = provides[SYSRELVER]
osVersionRelease = (sstr(h['name']), version, release)
return osVersionRelease
else:
for h in ts.dbMatch('Providename', "redhat-release"):
SYSRELVER = 'system-release(releasever)'
version = sstr(h['version'])
release = sstr(h['release'])
if SYSRELVER in h['providename']:
provides = dict(zip(h['providename'], h['provideversion']))
release = '%s-%s' % (version, release)
version = provides[SYSRELVER]
osVersionRelease = (sstr(h['name']), version, release)
return osVersionRelease
else:
for h in ts.dbMatch('Providename', "distribution-release"):
osVersionRelease = (sstr(h['name']), sstr(h['version']), sstr(h['release']))
# zypper requires a exclusive lock on the rpmdb. So we need
# to close it here.
ts.ts.closeDB()
return osVersionRelease
else:
raise up2dateErrors.RpmError(
"Could not determine what version of Red Hat Linux you "\
"are running.\nIf you get this error, try running \n\n"\
"\t\trpm --rebuilddb\n\n")
开发者ID:lhellebr,项目名称:spacewalk,代码行数:35,代码来源:up2dateUtils.py
示例5: exceptionHandler
def exceptionHandler(type, value, tb):
log = up2dateLog.initLog()
sys.stderr.write(sstr(_("An error has occurred:") + "\n"))
if hasattr(value, "errmsg"):
sys.stderr.write(sstr(value.errmsg) + "\n")
log.log_exception(type, value, tb)
else:
sys.stderr.write(sstr(str(type) + "\n"))
log.log_exception(type, value, tb)
sys.stderr.write(sstr(_("See /var/log/up2date for more information") + "\n"))
开发者ID:m47ik,项目名称:uyuni,代码行数:11,代码来源:rhncli.py
示例6: validateFields
def validateFields(self):
if self.userNameEntry.value() == "":
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(USER_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.userNameEntry)
return 0
if self.passwordEntry.value() == "":
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(PASSWORD_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.passwordEntry)
return 0
try:
self.tui.alreadyRegistered = rhnreg.reserveUser(self.userNameEntry.value(), self.passwordEntry.value())
except up2dateErrors.ValidationError:
e = sys.exc_info()[1]
snack.ButtonChoiceWindow(self.screen, sstr(_("Error")), sstr(_("The server indicated an error:\n")) + sstr(e.errmsg), buttons = [sstr(_("OK"))])
self.g.setCurrent(self.userNameEntry)
return 0
except up2dateErrors.CommunicationError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen, _("There was an error communicating with the registration server:\n") + e.errmsg)
return 1
开发者ID:jdobes,项目名称:spacewalk,代码行数:26,代码来源:tui.py
示例7: _strip_characters
def _strip_characters(self, *args):
""" Strip characters, which are not allowed according:
http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
From spec:
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
"""
regexp = r'[\x00-\x09]|[\x0b-\x0c]|[\x0e-\x1f]'
result=[]
for item in args:
item_type = type(item)
if item_type == StringType or item_type == UnicodeType:
item = re.sub(regexp, '', sstr(item))
elif item_type == TupleType:
item = tuple(self._strip_characters(i) for i in item)
elif item_type == ListType:
item = [self._strip_characters(i) for i in item]
elif item_type == DictType or item_type == DictionaryType:
item = dict([(self._strip_characters(name, val)) for name, val in item.items()])
# else: some object - should take care of himself
# numbers - are safe
result.append(item)
if len(result) == 1:
return result[0]
else:
return tuple(result)
开发者ID:m47ik,项目名称:uyuni,代码行数:25,代码来源:rpclib.py
示例8: _add_proxy_headers
def _add_proxy_headers(self):
if not self.__username:
return
# Authenticated proxy
userpass = "%s:%s" % (self.__username, self.__password)
enc_userpass = base64.encodestring(i18n.bstr(userpass)).replace(i18n.bstr("\n"), i18n.bstr(""))
self.putheader("Proxy-Authorization", "Basic %s" % i18n.sstr(enc_userpass))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:7,代码来源:connections.py
示例9: __check_instance_lock
def __check_instance_lock():
lock = None
try:
lock = rhnLockfile.Lockfile('/var/run/rhn_check.pid')
except rhnLockfile.LockfileLockedException:
sys.stderr.write(sstr(_("Attempting to run more than one instance of rhn_check. Exiting.\n")))
sys.exit(0)
开发者ID:m47ik,项目名称:uyuni,代码行数:7,代码来源:rhn_check.py
示例10: write_log
def write_log(self, s):
log_name = self.cfg["logFile"] or "/var/log/up2date"
log_file = open(log_name, 'a')
msg = u"%s %s\n" % (ustr(self.log_info), ustr(s))
log_file.write(sstr(msg))
log_file.flush()
log_file.close()
开发者ID:jdobes,项目名称:spacewalk,代码行数:8,代码来源:up2dateLog.py
示例11: process
def process(self, data):
# Assume straight text/xml
self.data = data
# Content-Encoding header
if self.encoding == self.ENCODE_GZIP:
import gzip
encoding_name = self.encodings[self.ENCODE_GZIP][0]
self.set_header("Content-Encoding", encoding_name)
f = SmartIO(force_mem=1)
gz = gzip.GzipFile(mode="wb", compresslevel=COMPRESS_LEVEL, fileobj=f)
if sys.version_info[0] == 3:
gz.write(bstr(data))
else:
gz.write(sstr(data))
gz.close()
self.data = f.getvalue()
f.close()
elif self.encoding == self.ENCODE_ZLIB:
import zlib
encoding_name = self.encodings[self.ENCODE_ZLIB][0]
self.set_header("Content-Encoding", encoding_name)
obj = zlib.compressobj(COMPRESS_LEVEL)
self.data = obj.compress(data) + obj.flush()
elif self.encoding == self.ENCODE_GPG:
# XXX: fix me.
raise NotImplementedError(self.transfer, self.encoding)
encoding_name = self.encodings[self.ENCODE_GPG][0]
self.set_header("Content-Encoding", encoding_name)
# Content-Transfer-Encoding header
if self.transfer == self.TRANSFER_BINARY:
transfer_name = self.transfers[self.TRANSFER_BINARY]
self.set_header("Content-Transfer-Encoding", transfer_name)
self.set_header("Content-Type", "application/binary")
elif self.transfer == self.TRANSFER_BASE64:
import base64
transfer_name = self.transfers[self.TRANSFER_BASE64]
self.set_header("Content-Transfer-Encoding", transfer_name)
self.set_header("Content-Type", "text/base64")
self.data = base64.encodestring(self.data)
self.set_header("Content-Length", len(self.data))
rpc_version = __version__
if len(__version__.split()) > 1:
rpc_version = __version__.split()[1]
# other headers
self.set_header(
"X-Transport-Info", "Extended Capabilities Transport (C) Red Hat, Inc (version %s)" % rpc_version
)
self.__processed = 1
开发者ID:shastah,项目名称:spacewalk,代码行数:56,代码来源:transports.py
示例12: _run_oscap
def _run_oscap(arguments):
dev_null = open('/dev/null', mode="ab+")
c = _popen(['/usr/bin/oscap'] + arguments, stdout=dev_null.fileno())
ret = c.wait()
dev_null.close()
errors = sstr(c.stderr.read())
if ret != 0:
errors += 'xccdf_eval: oscap tool returned %i\n' % ret
log.log_debug('The oscap tool completed\n%s' % errors)
return errors
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:10,代码来源:scap.py
示例13: systemExit
def systemExit(code, msgs=None):
"Exit with a code and optional message(s). Saved a few lines of code."
if msgs is not None:
if type(msgs) not in [type([]), type(())]:
msgs = (msgs, )
for msg in msgs:
if hasattr(msg, 'value'):
msg = msg.value
sys.stderr.write(sstr(msg) + "\n")
sys.exit(code)
开发者ID:Bearlock,项目名称:spacewalk,代码行数:10,代码来源:spacewalk-channel.py
示例14: read_to_file
def read_to_file(self, file):
"""Copies the contents of this File object into another file
object"""
fd = self._get_file()
while 1:
buf = fd.read(self.bufferSize)
if not buf:
break
file.write(sstr(buf))
return file
开发者ID:TJM,项目名称:spacewalk,代码行数:10,代码来源:transports.py
示例15: diff_file
def diff_file(self, channel, path, local_file, revision):
r = self.repository
try:
info = r.get_raw_file_info(channel, path, revision)
if 'encoding' in info and info['file_contents']:
if info['encoding'] == 'base64':
info['file_contents'] = base64.decodestring(bstr(info['file_contents']))
else:
die(9, 'Error: unknown encoding %s' % info['encoding'])
except cfg_exceptions.RepositoryFileMissingError:
die(2, "Error: no such file %s (revision %s) in config channel %s"
% (path, revision, channel))
if os.path.islink(local_file) and info['filetype'] != 'symlink' :
die(8, "Cannot diff %s; the file on the system is a symbolic link while the file in the channel is not. " % local_file)
if info['filetype'] == 'symlink' and not os.path.islink(local_file) :
die(8, "Cannot diff %s; the file on the system is not a symbolic link while the file in the channel is. " % local_file)
if info['filetype'] == 'symlink':
src_link = info['symlink']
dest_link = os.readlink(local_file)
if src_link != os.readlink(local_file):
return "Symbolic links differ. Channel: '%s' -> '%s' System: '%s' -> '%s' \n " % (path,src_link, path, dest_link)
return ""
fromlines = sstr(info['file_contents']).splitlines(1)
tolines = open(local_file, 'r').readlines()
diff_output = difflib.unified_diff(fromlines, tolines, info['path'], local_file)
first_row = second_row = ''
try:
first_row = next(diff_output)
second_row = next(diff_output)
except StopIteration:
pass
file_stat = os.lstat(local_file)
local_info = r.make_stat_info(local_file, file_stat)
# rhel4 do not support selinux
if not 'selinux_ctx' in local_info:
local_info['selinux_ctx'] = ''
if 'selinux_ctx' not in info:
info['selinux_ctx'] = ''
if not first_row and not self.__attributes_differ(info, local_info):
return ""
else:
template = "--- %s\t%s\tattributes: %s %s %s %s\tconfig channel: %s\trevision: %s"
if 'modified' not in info:
info['modified'] = ''
first_row = template % (path, str(info['modified']), ostr_to_sym(info['filemode'], info['filetype']),
info['username'], info['groupname'], info['selinux_ctx'], channel,
info['revision'],
)
second_row = template % (local_file, f_date(datetime.fromtimestamp(local_info['mtime'])), ostr_to_sym(local_info['mode'], 'file'),
local_info['user'], local_info['group'], local_info['selinux_ctx'], 'local file', None
)
return first_row + '\n' + second_row + '\n' + ''.join(list(diff_output))
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:52,代码来源:rhncfg_diff.py
示例16: read_to_file
def read_to_file(self, file):
"""Copies the contents of this File object into another file
object"""
fd = self._get_file()
while 1:
buf = fd.read(self.bufferSize)
if not buf:
break
if sys.version_info[0] == 3:
file.write(bstr(buf))
else:
file.write(sstr(buf))
return file
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:13,代码来源:transports.py
示例17: save_unknown_domain_configs
def save_unknown_domain_configs(self, domain_uuids):
"""
This function saves the configuration for any domains whose UUIDs are
passed in the domain_uuids list. If the UUID is already known, it is
skipped.
"""
for uuid in domain_uuids:
uuid = sstr(uuid)
# If we already have a config for this uuid, skip it. Also, don't
# try to figure out a config for a host UUID.
if not is_host_uuid(uuid) and not self.is_known_config(uuid):
# The UUID is a formatted string. Turn it back into a number,
# since that's what libvirt wants.
dehyphenized_uuid = dehyphenize_uuid(uuid)
uuid_as_num = binascii.unhexlify(dehyphenized_uuid)
# Lookup the domain by its uuid.
try:
domain = self.conn.lookupByUUID(uuid_as_num)
except libvirt.libvirtError:
lve = sys.exc_info()[1]
raise VirtualizationException("Failed to obtain handle to domain %s: %s" % (uuid, repr(lve)))
# Now grab the XML description of the configuration.
xml = domain.XMLDesc(0)
# Write the xml out to a file so that we can load it into our
# abstract DomainConfig object and manipulate it easily.
cfg_file_path = self.__write_xml_file(uuid, xml)
new_config = DomainConfig(self.__path, uuid)
# Don't record the config this time if the domain is
# installing; we don't want to restart the domain later and
# make it re-install itself.
if not new_config.isInstallerConfig():
# Now we'll reformat the configuration object so that it's
# valid the next time this domain runs..
self.__fixup_config_for_restart(new_config)
# The config is now prepared. Save it and move on to the
# next uuid.
new_config.save()
else:
# Remove the config file we just wrote.
os.unlink(cfg_file_path)
开发者ID:mcalmer,项目名称:spacewalk,代码行数:50,代码来源:domain_directory.py
示例18: getInstalledPackageList
def getInstalledPackageList(msgCallback = None, progressCallback = None,
getArch=None, getInfo = None):
""" Return list of packages. Package is hash with keys name, epoch,
version, release and optionaly arch and cookie
"""
pkg_list = []
if msgCallback != None:
msgCallback(_("Getting list of packages installed on the system"))
_ts = transaction.initReadOnlyTransaction()
count = 0
total = 0
for h in _ts.dbMatch():
if h == None:
break
count = count + 1
total = count
count = 0
for h in _ts.dbMatch():
if h == None:
break
package = {
'name': sstr(h['name']),
'epoch': h['epoch'],
'version': sstr(h['version']),
'release': sstr(h['release']),
'installtime': h['installtime']
}
if package['epoch'] == None:
package['epoch'] = ""
else: # convert it to string
package['epoch'] = "%s" % package['epoch']
if getArch:
package['arch'] = h['arch']
# the arch on gpg-pubkeys is "None"...
if package['arch']:
package['arch'] = sstr(package['arch'])
pkg_list.append(package)
elif getInfo:
if h['arch']:
package['arch'] = sstr(h['arch'])
if h['cookie']:
package['cookie'] = sstr(h['cookie'])
pkg_list.append(package)
else:
pkg_list.append(package)
if progressCallback != None:
progressCallback(count, total)
count = count + 1
pkg_list.sort(key=lambda x:(x['name'], x['epoch'], x['version'], x['release']))
return pkg_list
开发者ID:Bearlock,项目名称:spacewalk,代码行数:57,代码来源:rpmUtils.py
示例19: figureSerial
def figureSerial(caCertFilename, serialFilename, indexFilename):
""" for our purposes we allow the same serial number for server certs
BUT WE DO NOT ALLOW server certs and CA certs to share the same
serial number.
We blow away the index.txt file each time because we are less
concerned with matching serials/signatures between server.crt's.
"""
# what serial # is the ca cert using (we need to increment from that)
ret, outstream, errstream = rhn_popen(['/usr/bin/openssl', 'x509', '-noout',
'-serial', '-in', caCertFilename])
out = sstr(outstream.read())
outstream.close()
errstream.read()
errstream.close()
assert not ret
caSerial = out.strip().split('=')
assert len(caSerial) > 1
caSerial = caSerial[1]
caSerial = eval('0x'+caSerial)
# initialize the serial value (starting at whatever is in
# serialFilename or 1)
serial = 1
if os.path.exists(serialFilename):
serial = open(serialFilename, 'r').read().strip()
if serial:
serial = eval('0x'+serial)
else:
serial = 1
# make sure it is at least 1 more than the CA's serial code always
# REMEMBER: openssl will incremented the serial number each time
# as well.
if serial <= caSerial:
serial = incSerial(hex(caSerial))
serial = eval('0x' + serial)
serial = fixSerial(hex(serial))
# create the serial file if it doesn't exist
# write the digits to this file
open(serialFilename, 'w').write(serial+'\n')
os.chmod(serialFilename, int('0600',8))
# truncate the index.txt file. Less likely to have unneccessary clashes.
open(indexFilename, 'w')
os.chmod(indexFilename, int('0600',8))
return serial
开发者ID:mcalmer,项目名称:spacewalk,代码行数:49,代码来源:sslToolConfig.py
示例20: f_content
def f_content(path, name, is_binary):
statinfo = None
if os.access(path, os.R_OK):
f = open(path, ('r' if int(sys.version[0]) == 3 else 'U') + ('b' if is_binary else ''))
content = [sstr(i) for i in f.readlines()]
f.close()
statinfo = os.stat(path)
f_time = time.ctime(statinfo.st_mtime)
if not is_binary and content and content[-1] and content[-1][-1] != "\n":
content[-1] += "\n"
else:
content = []
f_time = time.ctime(0)
if not name:
name = path
return (content, name, f_time, statinfo)
开发者ID:mcalmer,项目名称:spacewalk,代码行数:16,代码来源:file_utils.py
注:本文中的rhn.i18n.sstr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论