本文整理汇总了Python中sage.misc.misc.sage_makedirs函数的典型用法代码示例。如果您正苦于以下问题:Python sage_makedirs函数的具体用法?Python sage_makedirs怎么用?Python sage_makedirs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sage_makedirs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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)
示例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__)
示例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
示例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")
示例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())
示例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()
示例9: path
def path():
from sage.misc.misc import sage_makedirs
sage_makedirs(PATH)
示例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)
示例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 ', '');
示例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)
示例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)
示例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)
示例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()