def _parse_command_opts(self, parser, args):
# Remove --with-X/--without-X options when processing command args
self.global_options = self.__class__.global_options
self.negative_opt = self.__class__.negative_opt
# First, expand any aliases
command = args[0]
aliases = self.get_option_dict('aliases')
while command in aliases:
src, alias = aliases[command]
del aliases[command] # ensure each alias can expand only once!
import shlex
args[:1] = shlex.split(alias, True)
command = args[0]
nargs = _Distribution._parse_command_opts(self, parser, args)
# Handle commands that want to consume all remaining arguments
cmd_class = self.get_command_class(command)
if getattr(cmd_class, 'command_consumes_arguments', None):
self.get_option_dict(command)['args'] = ("command line", nargs)
if nargs is not None:
return []
return nargs
python类split()的实例源码
def addbookmark(self):
""" Opens add bookmark dialog and gets url from url box"""
dialog = QDialog(self)
addbmkdialog = Add_Bookmark_Dialog()
addbmkdialog.setupUi(dialog)
addbmkdialog.titleEdit.setText(self.tabWidget.currentWidget().page().mainFrame().title())
addbmkdialog.addressEdit.setText(self.line.text())
if (dialog.exec_() == QDialog.Accepted):
url = unicode(addbmkdialog.addressEdit.text())
bmk = [unicode(addbmkdialog.titleEdit.text()), url]
self.bookmarks = importBookmarks(configdir+"bookmarks.txt")
self.bookmarks.insert(0, bmk)
exportBookmarks(configdir+"bookmarks.txt", self.bookmarks)
icon = self.tabWidget.currentWidget().icon()
if not icon.isNull():
icon.pixmap(16, 16).save(icon_dir + url.split('/')[2] + '.png')
def closeEvent(self, event):
"""This saves all settings, bookmarks, cookies etc. during window close"""
if self.confirm_before_quit:
confirm = QMessageBox.warning(self, 'Quit Browser ?', 'Are you sure to close the Browser',
'Quit', 'Cancel')
if confirm == 1 :
event.ignore()
return
self.savesettings()
cookiejar.exportCookies()
# Delete excess thumbnails
thumbnails = [ x for x in os.listdir(thumbnails_dir) ]
for fav in self.favourites:
if fav[2] in thumbnails:
thumbnails.remove(fav[2])
for f in thumbnails: os.remove(thumbnails_dir + f)
# Delete excess icons
icons = [ x for x in os.listdir(icon_dir) if x.endswith('.png') ]
for bmk in self.bookmarks:
if bmk[1].split('/')[2] + '.png' in icons:
icons.remove(bmk[1].split('/')[2] + '.png')
for f in icons: os.remove( icon_dir + f )
super(Main, self).closeEvent(event)
def accept_connections(s):
conn, addr = s.accept()
try:
data = ""
d = conn.recv(1024)
while d:
data += d
d = conn.recv(1024)
finally:
conn.close()
if data:
try:
urgency, host, title, body = shlex.split(data)
subprocess.call(["notify-send", "-u", urgency, "-a", "IRC %s" % host, escape(title), escape(body)])
except ValueError as e:
print e
except OSError as e:
print e
accept_connections(s)
def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
for arg in sys.argv:
if arg.startswith("@"):
expanded = True
with open(arg[1:],"r") as f:
for line in f.readlines():
new_args += shlex.split(line)
else:
new_args.append(arg)
if expanded:
print("esptool.py %s" % (" ".join(new_args[1:])))
sys.argv = new_args
satellite6-automation.py 文件源码
项目:satellite6_automation
作者: hambuergaer
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def get_environment_id(default_ccv):
translation_table = string.maketrans('-','_')
CONVERT_CCV = DEFAULT_CONTENT_VIEW.translate(translation_table)
CONVERT_ORGANIZATION = ORGANIZATION.translate(translation_table)
PUPPET_ENV = str("KT_" + CONVERT_ORGANIZATION + "_" + ENVIRONMENT + "_" + CONVERT_CCV)
cmd_get_environment_id = hammer_cmd + " --csv environment list"
try:
perform_cmd = subprocess.Popen(cmd_get_environment_id, shell=True, stdout=subprocess.PIPE)
puppet_env_id = perform_cmd.stdout.read()
for line in islice(puppet_env_id.strip().split("\n"), 1, None): # print output without CSV header
if PUPPET_ENV in line:
return line.split(",")[0]
break
except:
print log.ERROR + "ERROR: Puppet environment id not found. Please ensure that the Puppet environment " + PUPPET_ENV + " is configured properly in Satellite." + log.END
sys.exit(1)
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
assert_string_list(dist,attr,value)
for nsp in value:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
if '.' in nsp:
parent = '.'.join(nsp.split('.')[:-1])
if parent not in value:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
)
def _parse_command_opts(self, parser, args):
# Remove --with-X/--without-X options when processing command args
self.global_options = self.__class__.global_options
self.negative_opt = self.__class__.negative_opt
# First, expand any aliases
command = args[0]
aliases = self.get_option_dict('aliases')
while command in aliases:
src,alias = aliases[command]
del aliases[command] # ensure each alias can expand only once!
import shlex
args[:1] = shlex.split(alias,True)
command = args[0]
nargs = _Distribution._parse_command_opts(self, parser, args)
# Handle commands that want to consume all remaining arguments
cmd_class = self.get_command_class(command)
if getattr(cmd_class,'command_consumes_arguments',None):
self.get_option_dict(command)['args'] = ("command line", nargs)
if nargs is not None:
return []
return nargs
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
assert_string_list(dist,attr,value)
for nsp in value:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
if '.' in nsp:
parent = '.'.join(nsp.split('.')[:-1])
if parent not in value:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
)
def _parse_command_opts(self, parser, args):
# Remove --with-X/--without-X options when processing command args
self.global_options = self.__class__.global_options
self.negative_opt = self.__class__.negative_opt
# First, expand any aliases
command = args[0]
aliases = self.get_option_dict('aliases')
while command in aliases:
src,alias = aliases[command]
del aliases[command] # ensure each alias can expand only once!
import shlex
args[:1] = shlex.split(alias,True)
command = args[0]
nargs = _Distribution._parse_command_opts(self, parser, args)
# Handle commands that want to consume all remaining arguments
cmd_class = self.get_command_class(command)
if getattr(cmd_class,'command_consumes_arguments',None):
self.get_option_dict(command)['args'] = ("command line", nargs)
if nargs is not None:
return []
return nargs
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
assert_string_list(dist,attr,value)
for nsp in value:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
if '.' in nsp:
parent = '.'.join(nsp.split('.')[:-1])
if parent not in value:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
)
def parse_args(self, arg_string):
try:
self.args = self.parser.parse_args(shlex.split(arg_string))
return True
except BadArgumentsException:
return False
def loadavg(self):
with open('/proc/loadavg', 'r') as f:
load_1min, load_5min, load_15min = f.readline().split()[0:3]
return {
'1min': load_1min,
'5min': load_5min,
'15min': load_15min,
}
def cpustat(self, fullstat=False):
cpustat = {}
# REF: http://www.kernel.org/doc/Documentation/filesystems/proc.txt
fname = ('used', 'idle')
full_fname = ('user', 'nice', 'system', 'idle', 'iowait', 'irq',
'softirq', 'steal', 'guest', 'guest_nice')
cpustat['cpus'] = []
with open('/proc/stat', 'r') as f:
for line in f:
if line.startswith('cpu'):
fields = line.strip().split()
name = fields[0]
if not fullstat and name != 'cpu': continue;
stat = fields[1:]
stat = [int(i) for i in stat]
statall = sum(stat)
if fullstat:
while len(stat) < 10: stat.append(0)
stat = dict(zip(full_fname, stat))
else:
stat = [statall-stat[3], stat[3]]
stat = dict(zip(fname, stat))
stat['all'] = statall
if name == 'cpu':
cpustat['total'] = stat
else:
cpustat['cpus'].append(stat)
elif line.startswith('btime'):
btime = int(line.strip().split()[1])
cpustat['btime'] = time.strftime('%Y-%m-%d %X %Z',
time.localtime(btime))
return cpustat
def meminfo(self):
# OpenVZ may not have some varirables
# so init them first
mem_total = mem_free = mem_buffers = mem_cached = swap_total = swap_free = 0
with open('/proc/meminfo', 'r') as f:
for line in f:
if ':' not in line: continue
item, value = line.split(':')
value = int(value.split()[0]) * 1024;
if item == 'MemTotal':
mem_total = value
elif item == 'MemFree':
mem_free = value
elif item == 'Buffers':
mem_buffers = value
elif item == 'Cached':
mem_cached = value
elif item == 'SwapTotal':
swap_total = value
elif item == 'SwapFree':
swap_free = value
mem_used = mem_total - mem_free
swap_used = swap_total - swap_free
return {
'mem_total': b2h(mem_total),
'mem_used': b2h(mem_used),
'mem_free': b2h(mem_free),
'mem_buffers': b2h(mem_buffers),
'mem_cached': b2h(mem_cached),
'swap_total': b2h(swap_total),
'swap_used': b2h(swap_used),
'swap_free': b2h(swap_free),
'mem_used_rate': div_percent(mem_used, mem_total),
'mem_free_rate': div_percent(mem_free, mem_total),
'swap_used_rate': div_percent(swap_used, swap_total),
'swap_free_rate': div_percent(swap_free, swap_total),
}
def uname(self):
p = subprocess.Popen(shlex.split('uname -i'), stdout=subprocess.PIPE, close_fds=True)
hwplatform = p.stdout.read().strip()
p.wait()
uname = platform.uname()
return {
'kernel_name': uname[0],
'node': uname[1],
'kernel_release': uname[2],
'kernel_version': uname[3],
'machine': uname[4],
'processor': uname[5],
'platform': hwplatform,
}
def cpuinfo(self):
models = []
bitss = []
cpuids = []
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if 'model name' in line or 'physical id' in line or 'flags' in line:
item, value = line.strip().split(':')
item = item.strip()
value = value.strip()
if item == 'model name':
models.append(re.sub('\s+', ' ', value))
elif item == 'physical id':
cpuids.append(value)
elif item == 'flags':
if ' lm ' in value:
bitss.append('64bit')
else:
bitss.append('32bit')
cores = [{'model': x, 'bits': y} for x, y in zip(models, bitss)]
cpu_count = len(set(cpuids))
if cpu_count == 0: cpu_count = 1
return {
'cores': cores,
'cpu_count': cpu_count,
'core_count': len(cores),
}
def partinfo(self, uuid=None, devname=None):
"""Read partition info including uuid and filesystem.
You can specify uuid or devname to get the identified partition info.
If no argument provided, all partitions will return.
We read info from /etc/blkid/blkid.tab instead of call blkid command.
REF: http://linuxconfig.org/how-to-retrieve-and-change-partitions-universally-unique-identifier-uuid-on-linux
"""
blks = {}
p = subprocess.Popen(shlex.split('/sbin/blkid'), stdout=subprocess.PIPE, close_fds=True)
p.stdout.read()
p.wait()
# OpenVZ may not have this file
if not os.path.exists('/etc/blkid/blkid.tab'): return None
with open('/etc/blkid/blkid.tab') as f:
for line in f:
dom = parseString(line).documentElement
_fstype = dom.getAttribute('TYPE')
_uuid = dom.getAttribute('UUID')
_devname = dom.firstChild.nodeValue.replace('/dev/', '')
partinfo = {
'name': _devname,
'fstype': _fstype,
'uuid': _uuid,
}
if uuid and uuid == _uuid:
return partinfo
elif devname and devname == _devname:
return partinfo
else:
blks[_devname] = partinfo
if uuid or devname:
return None
else:
return blks
def autostart_list(self):
"""Return a list of the autostart service name.
"""
with open('/etc/inittab') as f:
for line in f:
if line.startswith('id:'):
startlevel = line.split(':')[1]
break
rcpath = '/etc/rc.d/rc%s.d/' % startlevel
services = [
os.path.basename(os.readlink(filepath))
for filepath in glob.glob('%s/S*' % rcpath)]
return services
#}}}
#{{{Tool
def set_params(self, message):
self.text_cont = message
self.text_words = message.split(' ')
#
# Define useful functions outside class.
#