本文整理汇总了Python中monty.string.is_string函数的典型用法代码示例。如果您正苦于以下问题:Python is_string函数的具体用法?Python is_string怎么用?Python is_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: product
def product(self, *items):
"""
Cartesian product of input iterables. Equivalent to nested for-loops.
.. code-block:: python
inp.product("tsmear", "ngkpt", [[2,2,2], [4,4,4]], [0.1, 0.2, 0.3])
"""
# Split items into varnames and values
for i, item in enumerate(items):
if not is_string(item): break
varnames, values = items[:i], items[i:]
if len(varnames) != len(values):
raise self.Error("The number of variables must equal the number of lists")
varnames = [ [varnames[i]] * len(values[i]) for i in range(len(values))]
varnames = itertools.product(*varnames)
values = itertools.product(*values)
idt = 0
for names, values in zip(varnames, values):
idt += 1
self[idt].set_vars(**{k: v for k, v in zip(names, values)})
if idt != self.ndtset:
raise self.Error("The number of configurations must equal ndtset while %d != %d" % (idt, self.ndtset))
开发者ID:kidaa,项目名称:abipy,代码行数:27,代码来源:input.py
示例2: add_file
def add_file(self, label, abifile, filter_abifile=None):
"""
Add a file to the robot with the given label.
Args:
label: String used to identify the file (must be unique, ax exceptions is
raised if label is already present.
abifile: Specify the file to be added. Accepts strings (filepath) or abipy file-like objects.
filter_abifile: Function that receives an ``abifile`` object and returns
True if the file should be added to the plotter.
"""
if is_string(abifile):
from abipy.abilab import abiopen
abifile = abiopen(abifile)
if filter_abifile is not None and not filter_abifile(abifile):
abifile.close()
return
# Open file here --> have to close it.
self._do_close[abifile.filepath] = True
if label in self._abifiles:
raise ValueError("label %s is already present!" % label)
self._abifiles[label] = abifile
开发者ID:gmatteo,项目名称:abipy,代码行数:25,代码来源:robots.py
示例3: add_file
def add_file(self, label, ncfile):
if is_string(ncfile):
from abipy.abilab import abiopen
ncfile = abiopen(ncfile)
self._do_close[ncfile.filepath] = True
self._ncfiles[label] = ncfile
开发者ID:ldamewood,项目名称:abipy,代码行数:7,代码来源:robots.py
示例4: open
def open(cls, obj, nids=None, **kwargs):
"""
Flexible constructor. obj can be a :class:`Flow` or a string with the directory containing the Flow.
nids is an optional list of :class:`Node` identifiers used to filter the set of :class:`Task` in the Flow.
"""
has_dirpath = False
if is_string(obj):
try:
obj = Flow.pickle_load(obj)
except:
has_dirpath = True
if not has_dirpath:
# We have a Flow. smeth is the name of the Task method used to open the file.
items = []
smeth = "open_" + cls.EXT.lower()
for task in obj.iflat_tasks(nids=nids): #, status=obj.S_OK):
open_method = getattr(task, smeth, None)
if open_method is None: continue
ncfile = open_method()
if ncfile is not None: items.append((task.pos_str, ncfile))
return cls(*items)
else:
# directory --> search for files with the appropriate extension and open it with abiopen.
if nids is not None: raise ValueError("nids cannot be used when obj is a directory.")
return cls.from_dir(obj)
开发者ID:davidwaroquiers,项目名称:abipy,代码行数:27,代码来源:robots.py
示例5: compare_d2de_scf_cycles
def compare_d2de_scf_cycles(self, others, show=True):
"""
Produce and returns a `matplotlib` figure comparing the DFPT self-consistent
cycle in self with the ones in others.
Args:
others: list of `AbinitOutputFile` objects or strings with paths to output files.
show: True to diplay plots.
"""
for i, other in enumerate(others):
if is_string(other): others[i] = self.__class__.from_file(other)
fig, figures = None, []
while True:
cycle = self.next_d2de_scf_cycle()
if cycle is None: break
fig = cycle.plot(show=False)
for i, other in enumerate(others):
other_cycle = other.next_d2de_scf_cycle()
if other_cycle is None: break
last = (i == len(others) - 1)
fig = other_cycle.plot(fig=fig, show=show and last)
if last: figures.append(fig)
self.seek(0)
for other in others: other.seek(0)
return figures
开发者ID:temok-mx,项目名称:abipy,代码行数:28,代码来源:mixins.py
示例6: asabistructure
def asabistructure(obj):
"""
Convert obj into an AbiStructure object. Accepts:
- AbiStructure instance
- Subinstances of pymatgen.
- File paths
"""
if isinstance(obj, AbiStructure):
return obj
if isinstance(obj, Structure):
# Promote
return AbiStructure(obj)
if is_string(obj):
# Handle file paths.
if os.path.isfile(obj):
if obj.endswith(".nc"):
structure = structure_from_etsf_file(obj)
else:
structure = Structure.from_file(obj)
# Promote
return AbiStructure(structure)
raise ValueError("Don't know how to convert object %s to an AbiStructure structure" % str(obj))
开发者ID:malusdiaz,项目名称:pymatgen,代码行数:28,代码来源:abiobjects.py
示例7: wxapp_events
def wxapp_events(root):
"""
Start up the AbinitOutputViewer application.
Args:
root:
Can be: None, filename, directory name or list of filenames.
None means that we just open the browser without accessing any file.
If root is a directory, we locate all the output files
starting from root and we visualize them in the main Frame.
"""
if root is None:
filenames = []
elif is_string(root):
root = os.path.abspath(root)
if os.path.isdir(root):
filenames = [os.path.join(root, f) for f in os.listdir(root) if f.endswith(".abo")]
else:
filenames = [root]
else:
filenames = root
class AbiEventsViewerApp(awx.App):
def OnInit(self):
frame = AbinitEventsNotebookFrame(None, filenames)
self.SetTopWindow(frame)
frame.Show()
return True
return AbiEventsViewerApp()
开发者ID:GkAntonius,项目名称:abipy,代码行数:31,代码来源:events.py
示例8: str2array
def str2array(obj, dtype=float):
if not is_string(obj): return np.asarray(obj)
if obj.startswith("*"):
raise ValueError("This case should be treated by the caller: %s" % str(obj))
s = expand_star_syntax(obj)
# Numpy does not understand "0.00d0 0.00d0"
s = s.lower().replace("d", "e")
return np.fromstring(s, sep=" ", dtype=dtype)
开发者ID:gmatteo,项目名称:abipy,代码行数:8,代码来源:abivars.py
示例9: from_chgcar_poscar
def from_chgcar_poscar(cls, chgcar, poscar):
"""
Build a :class`Density` object from Vasp data.
Args:
chgcar: Either string with the name of a CHGCAR file or :class:`Chgcar` pymatgen object.
poscar: Either string with the name of a POSCAR file or :class:`Poscar` pymatgen object.
.. warning:
The present version does not support non-collinear calculations.
The Chgcar object provided by pymatgen does not provided enough information
to understand if the calculation is collinear or no.
"""
if is_string(chgcar):
chgcar = Chgcar.from_file(chgcar)
if is_string(poscar):
poscar = Poscar.from_file(poscar, check_for_POTCAR=False, read_velocities=False)
nx, ny, nz = chgcar.dim
nspinor = 1
nsppol = 2 if chgcar.is_spin_polarized else 1
nspden = 2 if nsppol == 2 else 1
# Convert pymatgen chgcar data --> abipy representation.
abipy_datar = np.empty((nspden, nx, ny, nz))
if nspinor == 1:
if nsppol == 1:
abipy_datar = chgcar.data["total"]
elif nsppol == 2:
total, diff = chgcar.data["total"], chgcar.data["diff"]
abipy_datar[0] = 0.5 * (total + diff)
abipy_datar[1] = 0.5 * (total - diff)
else:
raise ValueError("Wrong nspden %s" % nspden)
else:
raise NotImplementedError("nspinor == 2 requires more info in Chgcar")
# density in Chgcar is multiplied by volume!
abipy_datar /= poscar.structure.volume
return cls(nspinor=nspinor, nsppol=nsppol, nspden=nspden, datar=abipy_datar,
structure=poscar.structure, iorder="c")
开发者ID:gmatteo,项目名称:abipy,代码行数:45,代码来源:fields.py
示例10: get_values
def get_values(self, keys):
"""Return a list of values associated to a particular list of keys"""
if is_string(keys):
return [s.__dict__[keys] for s in self.sections]
else:
values = []
for k in keys:
values.append([s.__dict__[k] for s in self.sections])
return values
开发者ID:sonium0,项目名称:pymatgen,代码行数:9,代码来源:abitimer.py
示例11: check_var
def check_var(v, w):
_error = False
if isinstance(v, int):
_error = check_int(v, w)
elif isinstance(v, float):
_error = check_float(v, w)
elif is_string(v):
_error = check_str(v, w)
return _error
开发者ID:gpetretto,项目名称:abipy,代码行数:9,代码来源:testing.py
示例12: _select_hosts
def _select_hosts(self, hostnames):
"""
Helper function to select hostnames.
Receives None, string or list of strings and returns a list of hostnames.
"""
if hostnames is None:
return self.hostnames()
else:
return [hostnames] if is_string(hostnames) else hostnames
开发者ID:GkAntonius,项目名称:abipy,代码行数:9,代码来源:clusters.py
示例13: any2sch
def any2sch(obj):
"""Convert string or int to Schoenflies symbol. Returns None if invalid input"""
if is_string(obj):
if obj in sch_symbols:
return obj
else:
# Try Hermann-Mauguin
return herm2sch(obj)
else:
# Spacegroup ID?
return spgid2sch(obj)
开发者ID:akakcolin,项目名称:abipy,代码行数:11,代码来源:symmetries.py
示例14: _get_structure
def _get_structure(self, obj):
"""Extract the structure from the input object."""
if isinstance(obj, Structure):
self.structure = obj
elif is_string(obj):
self.structure = abiopen(obj).structure
elif hasattr(obj, "structure"):
self.structure = obj.structure
else:
raise TypeError("Don't know how to extract the structure from %s" % str(obj))
开发者ID:davidwaroquiers,项目名称:abipy,代码行数:13,代码来源:structure.py
示例15: to_csv
def to_csv(self, fileobj=sys.stdout):
"""Write data on file fileobj using CSV format."""
openclose = is_string(fileobj)
if openclose:
fileobj = open(fileobj, "w")
for (idx, section) in enumerate(self.sections):
fileobj.write(section.to_csvline(with_header=(idx == 0)))
fileobj.flush()
if openclose:
fileobj.close()
开发者ID:sonium0,项目名称:pymatgen,代码行数:13,代码来源:abitimer.py
示例16: as_event_class
def as_event_class(obj):
"""
Convert obj into a subclass of AbinitEvent.
obj can be either a class or a string with the class name or the YAML tag
"""
if is_string(obj):
for c in all_subclasses(AbinitEvent):
if c.__name__ == obj or c.yaml_tag == obj: return c
raise ValueError("Cannot find event class associated to %s" % obj)
# Assume class.
assert obj in all_subclasses(AbinitEvent)
return obj
开发者ID:ychaojia,项目名称:pymatgen,代码行数:13,代码来源:events.py
示例17: sendmail
def sendmail(subject, text, mailto, sender=None):
"""
Sends an e-mail with unix sendmail.
Args:
subject: String with the subject of the mail.
text: String with the body of the mail.
mailto: String or list of string with the recipients.
sender: string with the sender address.
If sender is None, [email protected] is used.
Returns:
Exit status
"""
def user_at_host():
from socket import gethostname
return os.getlogin() + "@" + gethostname()
# Body of the message.
try:
sender = user_at_host() if sender is None else sender
except OSError:
sender = 'ab[email protected]'
if is_string(mailto): mailto = [mailto]
from email.mime.text import MIMEText
mail = MIMEText(text)
mail["Subject"] = subject
mail["From"] = sender
mail["To"] = ", ".join(mailto)
msg = mail.as_string()
# sendmail works much better than the python interface.
# Note that sendmail is available only on Unix-like OS.
from subprocess import Popen, PIPE
import sys
sendmail = which("sendmail")
if sendmail is None: return -1
if sys.version_info[0] < 3:
p = Popen([sendmail, "-t"], stdin=PIPE, stderr=PIPE)
else:
# msg is string not bytes so must use universal_newlines
p = Popen([sendmail, "-t"], stdin=PIPE, stderr=PIPE, universal_newlines=True)
outdata, errdata = p.communicate(msg)
return len(errdata)
开发者ID:czhengsci,项目名称:pymatgen,代码行数:49,代码来源:launcher.py
示例18: __init__
def __init__(self, node, exts=None):
"""
Args:
node: The task or the worfklow associated to the dependency or string with a filepath.
exts: Extensions of the output files that are needed for running the other tasks.
"""
self._node = Node.as_node(node)
if exts and is_string(exts): exts = exts.split()
# Extract extensions.
self.exts = [e for e in exts if not e.startswith("@")]
# Save getters
self.getters = [e for e in exts if e.startswith("@")]
开发者ID:tallakahath,项目名称:pymatgen,代码行数:15,代码来源:nodes.py
示例19: __init__
def __init__(self, parent, filepaths, **kwargs):
"""
Args:
parent:
parent window
filepaths:
List of file paths.
"""
super(FileListPanel, self).__init__(parent, -1, **kwargs)
if filepaths is not None and is_string(filepaths):
filepaths = [filepaths]
self.filepaths = filepaths if filepaths is not None else []
self.filepaths = map(os.path.abspath, self.filepaths)
self.BuildUi()
开发者ID:gmatteo,项目名称:abipy,代码行数:17,代码来源:browser.py
示例20: sendmail
def sendmail(subject, text, mailto, sender=None):
"""
Sends an e-mail with unix sendmail.
Args:
subject:
String with the subject of the mail.
text:
String with the body of the mail.
mailto:
String or list of string with the recipients.
sender:
string with the sender address.
If sender is None, [email protected] is used.
Returns:
exit status
"""
def user_at_host():
from socket import gethostname
return os.getlogin() + "@" + gethostname()
# Body of the message.
sender = user_at_host() if sender is None else sender
if is_string(mailto): mailto = [mailto]
from email.mime.text import MIMEText
mail = MIMEText(text)
mail["Subject"] = subject
mail["From"] = sender
mail["To"] = ", ".join(mailto)
msg = mail.as_string()
# sendmail works much better than the python interface.
# Note that sendmail is available only on Unix-like OS.
from subprocess import Popen, PIPE
sendmail = which("sendmail")
if sendmail is None: return -1
p = Popen([sendmail, "-t"], stdin=PIPE, stderr=PIPE)
outdata, errdata = p.communicate(msg)
return len(errdata)
开发者ID:malusdiaz,项目名称:pymatgen,代码行数:45,代码来源:launcher.py
注:本文中的monty.string.is_string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论