本文整理汇总了Python中sage.misc.misc.sage_makedirs函数的典型用法代码示例。如果您正苦于以下问题:Python sage_makedirs函数的具体用法?Python sage_makedirs怎么用?Python sage_makedirs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sage_makedirs函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: copy_gz_file
def copy_gz_file(gz_source, bz_destination):
"""
Decompress a gzipped file and install the bzipped verson. This is
used by SloaneEncyclopedia.install_from_gz to install several
gzipped OEIS database files.
INPUT:
- ``gz_source`` - string. The name of the gzipped file.
- ``bz_destination`` - string. The name of the newly compressed file.
"""
import gzip
from sage.misc.misc import sage_makedirs
# Read the gzipped input
try:
gz_input = gzip.open(gz_source, 'r')
db_text = gz_input.read()
gz_input.close()
except IOError as msg:
raise IOError("Error reading gzipped input file:\n%s"%msg)
# Write the bzipped output
try:
sage_makedirs(os.path.dirname(bz_destination))
bz2_output = bz2.BZ2File(bz_destination, 'w')
bz2_output.write(db_text)
bz2_output.close()
except IOError as msg:
raise IOError("Error writing bzipped output file:\n%s"%msg)
开发者ID:Findstat,项目名称:sage,代码行数:31,代码来源:sloane.py
示例2: is_jvm_available
def is_jvm_available(self):
"""
Returns True if the Java Virtual Machine is available and False if not.
EXAMPLES:
Check that it returns a boolean::
sage: from sage.interfaces.jmoldata import JmolData
sage: JData = JmolData()
sage: type(JData.is_jvm_available())
<type 'bool'>
"""
#scratch file for Jmol errors and status
jmolscratch = os.path.join(DOT_SAGE, "sage_notebook.sagenb", "jmol_scratch")
if not os.path.exists(jmolscratch):
sage_makedirs(jmolscratch)
scratchout = os.path.join(jmolscratch,"jmolout.txt")
jout=open(scratchout,'w')
testjavapath = os.path.join(SAGE_LOCAL, "share", "jmol", "testjava.sh")
result = subprocess.call([testjavapath],stdout=jout)
jout.close()
if (result == 0):
return (True)
else:
return (False)
开发者ID:CETHop,项目名称:sage,代码行数:26,代码来源:jmoldata.py
示例3: dump_as_dict
def dump_as_dict(self, filename, keys):
from sage.misc.misc import sage_makedirs
X = self.as_dict(keys)
print "Dumping %s..."%filename
s = cPickle.dumps(X,2)
dir = "%s/pickles/"%SAGE_DATA
sage_makedirs(dir)
open("%s/%s"%(dir,filename), "w").write(s)
开发者ID:bgxcpku,项目名称:sagelib,代码行数:8,代码来源:db.py
示例4: __init__
def __init__(self, f, dir='func_persist'):
from sage.misc.misc import sage_makedirs
self.__func = f
self.__dir = dir
sage_makedirs(dir)
self.__doc__ = '%s%s%s'%(\
f.func_name,
inspect.formatargspec(*inspect.getargs(f.func_code)),
f.__doc__)
开发者ID:CETHop,项目名称:sage,代码行数:9,代码来源:func_persist.py
示例5: citation_dir
def citation_dir(app):
# Split app.outdir in 3 parts: SAGE_DOC/TYPE/TAIL where TYPE
# is a single directory and TAIL can contain multiple directories.
# The citation dir is then SAGE_DOC/inventory/TAIL.
assert app.outdir.startswith(SAGE_DOC)
rel = app.outdir[len(SAGE_DOC):]
dirs = rel.split(os.sep)
# If SAGE_DOC does not end with a slash, rel will start with
# a slash giving an empty dirs[0]. Remove this:
if not dirs[0]:
dirs.pop(0)
dirs = [SAGE_DOC, "inventory"] + dirs[1:]
citedir = os.path.join(*dirs)
sage_makedirs(citedir)
return citedir
开发者ID:saraedum,项目名称:sage-renamed,代码行数:15,代码来源:multidocs.py
示例6: _init
def _init(self, path):
"""
Create the database from scratch from the PARI files on John Jones's
web page, downloaded (e.g., via wget) to a local directory, which
is specified as path above.
INPUT:
- ``path`` - (default works on William Stein install.)
path must be the path to Jones's Number_Fields directory
http://hobbes.la.asu.edu/Number_Fields These files should have
been downloaded using wget.
EXAMPLE: This is how to create the database from scratch, assuming
that the number fields are in the default directory above: From a
cold start of Sage::
sage: J = JonesDatabase()
sage: J._init() # not tested
...
This takes about 5 seconds.
"""
from sage.misc.misc import sage_makedirs
n = 0
x = PolynomialRing(RationalField(), "x").gen()
self.root = {}
self.root[tuple([])] = [x - 1]
if not os.path.exists(path):
raise IOError("Path %s does not exist." % path)
for X in os.listdir(path):
if X[-4:] == "solo":
Z = path + "/" + X
print(X)
for Y in os.listdir(Z):
if Y[-3:] == ".gp":
self._load(Z, Y)
sage_makedirs(JONESDATA)
save(self.root, JONESDATA + "/jones.sobj")
开发者ID:JasYoung314,项目名称:sage,代码行数:42,代码来源:jones.py
示例7: save_preview
def save_preview(self):
"""
Save the preview PNG image
See :meth:`preview_filename`.
EXAMPLES::
sage: from sage.repl.rich_output.backend_sagenb import SageNbOutputSceneJmol
sage: j = SageNbOutputSceneJmol.example()
sage: import shutil
sage: shutil.rmtree('.jmol_images', ignore_errors=True)
sage: j.save_preview()
sage: os.listdir('.jmol_images')
['sage1-size32.jmol.png']
"""
from sage.misc.misc import sage_makedirs
sage_makedirs('.jmol_images')
self.preview_png.save_as(self.preview_filename())
world_readable(self.preview_filename())
开发者ID:Findstat,项目名称:sage,代码行数:20,代码来源:backend_sagenb.py
示例8: __init__
def __init__(self, dir=None, debug=False, viewer=None):
from sage.misc.misc import sage_makedirs
if dir is None:
dir = misc.DOT_SAGE + 'log'
self._time = time.strftime('%Y-%m-%d-%H%M%S')
dir = os.path.join(os.path.abspath(dir), 'log-' + self._time)
sage_makedirs(dir)
self._debug = debug
self._n = 0
self._dir = dir
self._filename = os.path.join(dir, self._filename())
self._output = __IPYTHON__.output_hist
self._input = __IPYTHON__.input_hist_raw
self._text = ''
self._after_output = False
self._init()
self._input_text = ''
self._stopped = False
self._viewer = viewer
loggers.append(self)
print('Now logging to ' + self._filename)
self._update()
self.view()
开发者ID:bgxcpku,项目名称:sagelib,代码行数:23,代码来源:log.py
示例9: path
def path():
from sage.misc.misc import sage_makedirs
sage_makedirs(PATH)
开发者ID:CETHop,项目名称:sage,代码行数:3,代码来源:db.py
示例10: _start
def _start(self, alt_message=None, block_during_init=True):
from sage.misc.misc import sage_makedirs
self.quit() # in case one is already running
global failed_to_start
self._session_number += 1
current_path = os.path.abspath('.')
dir = self.__path
sage_makedirs(dir)
os.chdir(dir)
#If the 'SAGE_PEXPECT_LOG' environment variable is set and
#the current logfile is None, then set the logfile to be one
#in .sage/pexpect_logs/
if self.__logfile is None and 'SAGE_PEXPECT_LOG' in os.environ:
from sage.env import DOT_SAGE
logs = '%s/pexpect_logs'%DOT_SAGE
sage_makedirs(logs)
filename = '%s/%s-%s-%s-%s.log'%(logs, self.name(), os.getpid(), id(self), self._session_number)
self.__logfile = open(filename, 'w')
cmd = self.__command
if self.__verbose_start:
print cmd
print "Starting %s"%cmd.split()[0]
try:
if self.__remote_cleaner and self._server:
c = 'sage-native-execute ssh %s "nohup sage -cleaner" &'%self._server
os.system(c)
# Unset some environment variables for the children to
# reduce the chances they do something complicated breaking
# the terminal interface.
# See Trac #12221 and #13859.
pexpect_env = dict(os.environ)
pexpect_del_vars = ['TERM', 'COLUMNS']
for i in pexpect_del_vars:
try:
del pexpect_env[i]
except KeyError:
pass
self._expect = pexpect.spawn(cmd, logfile=self.__logfile, env=pexpect_env)
if self._do_cleaner():
cleaner.cleaner(self._expect.pid, cmd)
except (ExceptionPexpect, pexpect.EOF, IndexError):
self._expect = None
self._session_number = BAD_SESSION
failed_to_start.append(self.name())
raise RuntimeError("Unable to start %s because the command '%s' failed.\n%s"%(
self.name(), cmd, self._install_hints()))
os.chdir(current_path)
self._expect.timeout = self.__max_startup_time
#self._expect.setmaxread(self.__maxread)
self._expect.maxread = self.__maxread
self._expect.delaybeforesend = 0
try:
self._expect.expect(self._prompt)
except (pexpect.TIMEOUT, pexpect.EOF) as msg:
self._expect = None
self._session_number = BAD_SESSION
failed_to_start.append(self.name())
raise RuntimeError("Unable to start %s"%self.name())
self._expect.timeout = None
# Calling tcsetattr earlier exposes bugs in various pty
# implementations, see :trac:`16474`. Since we haven't
# **written** anything so far it is safe to wait with
# switching echo off until now.
if not self._terminal_echo:
self._expect.setecho(0)
with gc_disabled():
if block_during_init:
for X in self.__init_code:
self.eval(X)
else:
for X in self.__init_code:
self._send(X)
开发者ID:Etn40ff,项目名称:sage,代码行数:84,代码来源:expect.py
示例11: sage_makedirs
- ``bz_destination`` - string. The name of the newly compressed file.
"""
import gzip
from sage.misc.misc import sage_makedirs
# Read the gzipped input
try:
gz_input = gzip.open(gz_source, 'r')
db_text = gz_input.read()
gz_input.close()
except IOError, msg:
raise IOError, "Error reading gzipped input file:\n%s"%msg
# Write the bzipped output
try:
sage_makedirs(os.path.dirname(bz_destination))
bz2_output = bz2.BZ2File(bz_destination, 'w')
bz2_output.write(db_text)
bz2_output.close()
except IOError, msg:
raise IOError, "Error writing bzipped output file:\n%s"%msg
def parse_sequence(text):
entry = re.compile(r'%(?P<letter>[A-Za-z]) A(?P<num>\d{6}) (?P<body>.*)$')
unsigned, signed, list = [], [], []
description = ''
seqnum = -1
# Fix broken lines: the next line is indented.
text = text.replace('\n ', '');
开发者ID:bgxcpku,项目名称:sagelib,代码行数:31,代码来源:sloane.py
示例12: path
def path():
from sage.misc.superseded import deprecation
deprecation(17653, 'The sage.misc.db module is deprecated, use the load/save functions from sage.structure.sage_object instead')
from sage.misc.misc import sage_makedirs
sage_makedirs(PATH)
开发者ID:BlairArchibald,项目名称:sage,代码行数:5,代码来源:db.py
示例13: _start
def _start(self, alt_message=None, block_during_init=True):
from sage.misc.misc import sage_makedirs
self.quit() # in case one is already running
self._session_number += 1
if self.__logfile is None:
# If the 'SAGE_PEXPECT_LOG' environment variable is set and
# there is no logfile already defined, then create a
# logfile in .sage/pexpect_logs/
if self.__logfilename is None and 'SAGE_PEXPECT_LOG' in os.environ:
from sage.env import DOT_SAGE
logs = os.path.join(DOT_SAGE, 'pexpect_logs')
sage_makedirs(logs)
self.__logfilename = '%s/%s-%s-%s-%s.log'%(logs, self.name(), os.getpid(), id(self), self._session_number)
if self.__logfilename is not None:
self.__logfile = open(self.__logfilename, 'w')
cmd = self.__command
if self.__verbose_start:
print cmd
print "Starting %s"%cmd.split()[0]
if self.__remote_cleaner and self._server:
c = 'sage-native-execute ssh %s "nohup sage -cleaner" &'%self._server
os.system(c)
# Unset some environment variables for the children to
# reduce the chances they do something complicated breaking
# the terminal interface.
# See Trac #12221 and #13859.
pexpect_env = dict(os.environ)
pexpect_del_vars = ['TERM', 'COLUMNS']
for i in pexpect_del_vars:
try:
del pexpect_env[i]
except KeyError:
pass
# Run child from self.__path
currentdir = os.getcwd()
os.chdir(self.__path)
try:
try:
self._expect = SageSpawn(cmd,
logfile=self.__logfile,
timeout=None, # no timeout
env=pexpect_env,
name=self._repr_(),
quit_string=self._quit_string())
except (ExceptionPexpect, pexpect.EOF) as e:
# Change pexpect errors to RuntimeError
raise RuntimeError("unable to start %s because the command %r failed: %s\n%s" %
(self.name(), cmd, e, self._install_hints()))
except BaseException:
self._expect = None
self._session_number = BAD_SESSION
raise
finally:
os.chdir(currentdir)
if self._do_cleaner():
cleaner.cleaner(self._expect.pid, cmd)
self._expect.maxread = self.__maxread
self._expect.delaybeforesend = 0
try:
self._expect.expect(self._prompt)
except (pexpect.TIMEOUT, pexpect.EOF):
self._expect = None
self._session_number = BAD_SESSION
raise RuntimeError("unable to start %s" % self.name())
self._expect.timeout = None
# Calling tcsetattr earlier exposes bugs in various pty
# implementations, see :trac:`16474`. Since we haven't
# **written** anything so far it is safe to wait with
# switching echo off until now.
if not self._terminal_echo:
self._expect.setecho(0)
with gc_disabled():
if block_during_init:
for X in self.__init_code:
self.eval(X)
else:
for X in self.__init_code:
self._send(X)
开发者ID:Findstat,项目名称:sage,代码行数:90,代码来源:expect.py
示例14: export_image
def export_image(self,
targetfile,
datafile, #name (path) of data file Jmol can read or script file telling it what to read or load
datafile_cmd='script', #"script" or "load"
image_type ='PNG', #PNG, JPG, GIF
figsize=5,
**kwds):
r"""
This executes JmolData.jar to make an image file.
INPUT:
- targetfile -- the full path to the file where the image
should be written.
- datafile -- full path to the data file Jmol can read or
text of a script telling Jmol what to read or load.
- datafile_cmd -- (default ``'script'``) ``'load'`` or ``'script'``
should be ``"load"`` for a data file.
- image_type -- (default ``"PNG"``) ``'PNG'`` ``'JPG'`` or ``'GIF'``
- figsize -- number (default 5) equal to (pixels/side)/100
OUTPUT:
Image file, .png, .gif or .jpg (default .png)
.. note::
Examples will generate an error message if a functional Java Virtual Machine (JVM)
is not installed on the machine the Sage instance is running on.
.. warning::
Programmers using this module should check that the JVM is
available before making calls to avoid the user getting
error messages. Check for the JVM using the function
:meth:`is_jvm_available`, which returns True if a JVM is available.
EXAMPLES:
Use Jmol to load a pdb file containing some DNA from a web data
base and make an image of the DNA. If you execute this in the
notebook, the image will appear in the output cell::
sage: from sage.interfaces.jmoldata import JmolData
sage: JData = JmolData()
sage: script = "load =1lcd;display DNA;moveto 0.0 { -473 -713 -518 59.94} 100.0 0.0 0.0 {21.17 26.72 27.295} 27.544636 {0.0 0.0 0.0} -25.287832 64.8414 0.0;"
sage: testfile = tmp_filename(ext="DNA.png")
sage: JData.export_image(targetfile=testfile,datafile=script,image_type="PNG") # optional -- internet
sage: print os.path.exists(testfile) # optional -- internet
True
Use Jmol to save an image of a 3-D object created in Sage.
This method is used internally by plot3d to generate static images.
This example doesn't have correct scaling::
sage: from sage.interfaces.jmoldata import JmolData
sage: JData = JmolData()
sage: D=dodecahedron()
sage: from sage.misc.misc import SAGE_TMP
sage: archive_name=os.path.join(SAGE_TMP, "archive.jmol.zip")
sage: D.export_jmol(archive_name) #not scaled properly...need some more steps.
sage: testfile = os.path.join(SAGE_TMP, "testimage.png")
sage: script = 'set defaultdirectory "%s"\n script SCRIPT\n'%archive_name
sage: JData.export_image(targetfile =testfile,datafile = script, image_type="PNG") # optional -- java
sage: print os.path.exists(testfile) # optional -- java
True
"""
if (self.is_jvm_available()):
# Set up paths, file names and scripts
jmolpath = os.path.join(SAGE_LOCAL, "share", "jmol", "JmolData.jar")
launchscript = ""
if (datafile_cmd!='script'):
launchscript = "load "
launchscript = launchscript + datafile
#print launchscript
imagescript = "write "+ image_type +" "+targetfile+"\n"
#print imagescript
sizeStr = "%sx%s" %(figsize*100,figsize*100)
#scratch file for Jmol errors and status
jmolscratch = os.path.join(DOT_SAGE, "sage_notebook.sagenb", "jmol_scratch")
if not os.path.exists(jmolscratch):
sage_makedirs(jmolscratch)
scratchout = os.path.join(jmolscratch,"jmolout.txt")
jout=open(scratchout,'w')
#now call the java application and write the file.
result = subprocess.call(["java","-Xmx512m","-Djava.awt.headless=true","-jar",jmolpath,"-iox","-g",sizeStr,"-J",launchscript,"-j",imagescript],stdout=jout)
jout.close()
else:
errStr = "Java Virtual Machine not available.\n"
errStr +="This should be checked before calling JmolData().export_image().\n"
errStr +="Use JmolData().is_jvm_available() to check.\n"
errStr +="Administrator should install JVM."
raise JmolDataError(errStr)
开发者ID:CETHop,项目名称:sage,代码行数:99,代码来源:jmoldata.py
示例15: _start
def _start(self, alt_message=None, block_during_init=True):
from sage.misc.misc import sage_makedirs
self.quit() # in case one is already running
global failed_to_start
self._session_number += 1
current_path = os.path.abspath('.')
dir = self.__path
sage_makedirs(dir)
os.chdir(dir)
#If the 'SAGE_PEXPECT_LOG' environment variable is set and
#the current logfile is None, then set the logfile to be one
#in .sage/pexpect_logs/
if self.__logfile is None and 'SAGE_PEXPECT_LOG' in os.environ:
from sage.misc.all import DOT_SAGE
logs = '%s/pexpect_logs'%DOT_SAGE
sage_makedirs(logs)
filename = '%s/%s-%s-%s-%s.log'%(logs, self.name(), os.getpid(), id(self), self._session_number)
self.__logfile = open(filename, 'w')
cmd = self.__command
if self.__verbose_start:
print cmd
print "Starting %s"%cmd.split()[0]
try:
if self.__remote_cleaner and self._server:
c = 'sage-native-execute ssh %s "nohup sage -cleaner" &'%self._server
os.system(c)
# Unset $TERM for the children to reduce the chances they do
# something complicated breaking the terminal interface.
# See Trac #12221.
pexpect_env = dict(os.environ)
try:
del pexpect_env["TERM"]
except KeyError:
pass
self._expect = pexpect.spawn(cmd, logfile=self.__logfile, env=pexpect_env)
if self._do_cleaner():
cleaner.cleaner(self._expect.pid, cmd)
except (ExceptionPexpect, pexpect.EOF, IndexError):
self._expect = None
self._session_number = BAD_SESSION
failed_to_start.append(self.name())
raise RuntimeError, "Unable to start %s because the command '%s' failed.\n%s"%(
self.name(), cmd, self._install_hints())
os.chdir(current_path)
self._expect.timeout = self.__max_startup_time
#self._expect.setmaxread(self.__maxread)
self._expect.maxread = self.__maxread
self._expect.delaybeforesend = 0
try:
self._expect.expect(self._prompt)
except (pexpect.TIMEOUT, pexpect.EOF), msg:
self._expect = None
self._session_number = BAD_SESSION
failed_to_start.append(self.name())
raise RuntimeError, "Unable to start %s"%self.name()
开发者ID:williamstein,项目名称:sagelib,代码行数:65,代码来源:expect.py
示例16: sage_makedirs
import os
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import RationalField
from sage.rings.arith import GCD
import sage.misc.db as db
from sage.misc.misc import SAGE_ROOT, sage_makedirs
# TODO:
# I messed up and now self.d is i and self.i is d,
# i.e., the degree and number are swapped.
PATH = SAGE_ROOT + "/src/tables/modular/gamma0/db/"
sage_makedirs(PATH)
class ModularForm:
def __init__(self, N, d, i, Wq, r, charpolys, disc):
self.N = N
self.d = d
self.i = i
self.Wq = Wq
self.r = r
self.charpolys = charpolys
self.disc = disc
def __repr__(self):
s = "Modular form: level %s, degree %s, number %s"%(
self.N,self.d,self.i) + \
", Wq: %s, an rank bnd: %s"%(
self.Wq, self.r)
开发者ID:bgxcpku,项目名称:sagelib,代码行数:31,代码来源:conv.py
示例17: cython
#.........这里部分代码省略.........
base = os.path.abspath(filename)
base = sanitize(base)
# This is the *temporary* directory where we store the pyx file.
# This is deleted when Sage exits, which means pyx files must be
# rebuilt every time Sage is restarted at present.
target_dir = os.path.join(SPYX_TMP, base)
# Build directory for Cython/distutils
build_dir = os.path.join(target_dir, "build")
if os.path.exists(target_dir):
# There is already a module here. Maybe we do not have to rebuild?
# Find the name.
if use_cache:
from sage.misc.sageinspect import loadable_module_extension
prev_so = [F for F in os.listdir(target_dir) if F.endswith(loadable_module_extension())]
if len(prev_so) > 0:
prev_so = prev_so[0] # should have length 1 because of deletes below
if os.path.getmtime(filename) <= os.path.getmtime('%s/%s'%(target_dir, prev_so)):
# We do not have to rebuild.
return prev_so[:-len(loadable_module_extension())], target_dir
# Delete all ordinary files in target_dir
for F in os.listdir(target_dir):
G = os.path.join(target_dir, F)
if os.path.isdir(G):
continue
try:
os.unlink(G)
except OSError:
pass
else:
sage_makedirs(target_dir)
if create_local_so_file:
name = base
else:
global sequence_number
if base not in sequence_number:
sequence_number[base] = 0
name = '%s_%s'%(base, sequence_number[base])
# increment the sequence number so will use a different one next time.
sequence_number[base] += 1
if compile_message:
print("Compiling {}...".format(filename), file=sys.stderr)
sys.stderr.flush()
with open(filename) as f:
(preparsed, libs, includes, language, additional_source_files,
extra_args, libdirs) = _pyx_preparse(f.read())
# New filename with preparsed code.
# NOTE: if we ever stop preparsing, we should still copy the
# original file to the target directory.
pyxfile = os.path.join(target_dir, name + ".pyx")
with open(pyxfile, 'w') as f:
f.write(preparsed)
extra_sources = []
for fname in additional_source_files:
fname = fname.replace("$SAGE_SRC", SAGE_SRC)
fname = fname.replace("$SAGE_LOCAL", SAGE_LOCAL)
extra_sources.append(fname)
开发者ID:saraedum,项目名称:sage-renamed,代码行数:67,代码来源:cython.py
注:本文中的sage.misc.misc.sage_makedirs函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论