本文整理汇总了Python中tempfile.NamedTemporaryFile.readlines方法的典型用法代码示例。如果您正苦于以下问题:Python NamedTemporaryFile.readlines方法的具体用法?Python NamedTemporaryFile.readlines怎么用?Python NamedTemporaryFile.readlines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.NamedTemporaryFile
的用法示例。
在下文中一共展示了NamedTemporaryFile.readlines方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: modify_guest
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def modify_guest(self):
# We swap out the default kickstart for one that forces mptspi
# This results in a bootable guest both during KVM customize and when
# run on vsphere
# By adding this at JEOS install time we leave open the possibility
# of modifying the module/boot environment during customization,
# for example, via the install of vmware tools.
# Use this just to get a known unique temp file name
new_kickstart = NamedTemporaryFile(delete = False)
new_kickstart_name = new_kickstart.name
new_kickstart.close()
# This step does the rootpw substitution for us
# modified file ends up in new_kickstart_name
# This is slightly naughty since we use an internal Oz function
self.guest._copy_kickstart(new_kickstart_name)
# read the now root-pw-substituted kickstart
new_kickstart = open(new_kickstart_name, "r")
ks_lines = new_kickstart.readlines()
new_kickstart.close()
# Add our device line
new_kickstart = open(new_kickstart_name, "w")
for ks_line in ks_lines:
new_kickstart.write(ks_line)
if re.match("install", ks_line):
new_kickstart.write("device scsi mptspi\n")
new_kickstart.close()
# Tell Oz that we want it to use this ks.cfg rather than the built in one
self.guest.auto = new_kickstart_name
示例2: solve
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def solve(self, cnf):
s = Solution()
infile = NamedTemporaryFile(mode='w')
outfile = NamedTemporaryFile(mode='r')
io = DimacsCnf()
infile.write(io.tostring(cnf))
infile.flush()
ret = call(self.command % (infile.name, outfile.name), shell=True)
infile.close()
if ret != 10:
return s
s.success = True
lines = outfile.readlines()[1:]
for line in lines:
varz = line.split(" ")[:-1]
for v in varz:
v = v.strip()
value = v[0] != '-'
v = v.lstrip('-')
vo = io.varobj(v)
s.varmap[vo] = value
# Close deletes the tmp files
outfile.close()
return s
示例3: test_newline_at_EOF
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def test_newline_at_EOF():
"""http://stackoverflow.com/a/729795"""
f = NamedTemporaryFile(delete=False)
prop = Properties(OrderedDict([
("a", "b"),
("c", "d"),
("e", "f")
]))
prop.save(f.name)
with open(f.name) as f:
lastline = f.readlines()[-1]
os.remove(f.name)
assert lastline.endswith("\n")
示例4: test_startup_script
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def test_startup_script(self):
self.command.contact_group_info = [{
'account': '[email protected]',
'key': 'conv1',
'contacts_csv': 'contacts.csv',
}]
self.command.conversation_info = [{
'account': '[email protected]',
'key': 'conv1',
'start': True,
}, {
'account': '[email protected]',
'key': 'conv2',
'start': False,
}]
self.command.router_info = [{
'account': '[email protected]',
'key': 'router1',
'start': False,
}, {
'account': '[email protected]',
'key': 'router2',
'start': True,
}]
startup_tmpfile = NamedTemporaryFile()
self.command.mk_filename = lambda fn, s: startup_tmpfile.name
self.command.write_startup_script()
startup_tmpfile.flush()
lines = [l.strip('\n') for l in startup_tmpfile.readlines()[3:]
if l.strip() != '']
self.assertEqual(lines, [
'#!/bin/bash',
'./go-admin.sh go_import_contacts ' # cont.
'--email-address [email protected] \\',
' --contacts contacts.csv --group conv1',
'echo "Starting conversation: conv1"',
'./go-admin.sh go_manage_conversation ' # cont.
'--email-address [email protected] \\',
' --conversation-key conv1 --start',
'echo "Starting router: router2"',
'./go-admin.sh go_manage_router ' # cont.
'--email-address [email protected] \\',
' --router-key router2 --start',
])
示例5: main
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def main():
parser = argparse.ArgumentParser(description="Check files.")
parser.add_argument('infile', type=str, nargs=1, help='Specify the path to the file of interest.')
parser.add_argument('-out', '--outfile', type=str, nargs=1, default=[None], help='Specify the path to the outfile.')
args = parser.parse_args()
infile = args.infile[0]
new_file = NamedTemporaryFile(delete=False)
with open(infile, 'rb') as f:
for line in f:
if not line.startswith('#'):
new_file.write(line)
for line in new_file.readlines():
if not is_number(line.rstrip().split('\t')[-1]):
print('du', line)
print('no errors')
fs = FileSort(new_file, args.outfile[0])
fs.sort()
示例6: process
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def process(infile):
fin = open(infile, "r")
cmd = []
for line in fin:
cmd.append(line.split('#')[0].strip())
a = NamedTemporaryFile()
foutName = a.name
a.close()
cmd.append("ELn %s.xml"%foutName)
ai = athenaObj.Interpreter('cgi')
for c in cmd:
ai.cmd(c)
a = open(foutName + ".sco", "r")
for line in a.readlines():
print line
示例7: load_target_types
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def load_target_types(ccdb_context, run_number):
mapping = {}
# make temp file to store CCDB info in
f = NamedTemporaryFile()
ccdb_context.process_command_line("dump /TARGET/target_type_list:" + str(run_number) + " > " + f.name)
# read in info
f.flush()
lines = f.readlines()
if len(lines) < 2:
print "Problem writing out CCDB table: /TARGET/target_type_list"
else:
# skip the first line, which is junk
for x in range(1, len(lines)):
vals = lines[x].split()
# index = int(vals[0])
mapping[int(vals[0])] = " ".join(vals[1:])
return mapping
示例8: solve
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def solve(self, cnf, variable = None, value = True,
translator = AIMA_to_Dimacs_Translator):
# if there are no clauses, then can't infer anything, so by default query result is unknown
# return Solution with success == None
# Note that this could be treated the same as failure.
# In PropKB_SAT.ask, this is OK as it will test if sT.success == sF.success
# and therefore will also return None
if not cnf: return Solution(None)
s = Solution()
infile = NamedTemporaryFile(mode='w')
outfile = NamedTemporaryFile(mode='r')
io = translator()
if variable:
dimacs = io.to_dimacs_string_set_variable_value(cnf, variable, value)
if dimacs:
infile.write(dimacs)
else:
return s
else:
infile.write(io.to_dimacs_string(cnf))
infile.flush()
ret = call(self.command % (infile.name, outfile.name), shell=True)
infile.close()
if ret != 10:
return s
s.success = True
lines = outfile.readlines()[1:]
for line in lines:
varz = line.split(' ')[:-1]
for v in varz:
v = v.strip()
value = v[0] != '-'
v = v.lstrip('-')
vo = io.varobj(v)
s.varmap[vo] = value
outfile.close()
return s
示例9: _convertDiff
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def _convertDiff(filename,do_diff=False):
m = Mesh(3)
sf = filename[filename.rindex('.'):]
if sf == '.smesh':
sf_o = '.ply'
else:
sf_o = '.smesh'
try:
m.parse( filename )
t = NamedTemporaryFile(suffix=sf_o)
m.write( t.name )
m.parse( t.name )
t2 = NamedTemporaryFile(suffix=sf)
fn2 = m.write( t2.name )
except Exception as e:
t.seek(0)
open( '/tmp/error.log', 'w').writelines( t.readlines() )
print((traceback.format_exc()))
raise e
#diff = difflib.unified_diff( open( filename ).readlines(), open( fn2 ).readlines() )
if do_diff:
print('-'*15 , 'generating diff output, convertDiff')
diff = difflib.HtmlDiff().make_file( open( filename ).readlines(), open( fn2 ).readlines() )
open( '%s.convert.diff.html'%filename ,'w' ).writelines(diff)
示例10: FileStore
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
class FileStore(object):
def __init__(self, proxy, processId, mode= 'r'):
'''
Gives r+w access to file on static instance via local tempfile.NamedTemproraryFile
'''
self.proxy= proxy
self.processId= processId
self.mode= mode
self.tmpFile= NamedTemporaryFile(mode= 'r+', prefix= self.processId, delete= True)
if 'r' in mode:
self.__get__()
def __get__(self):
'''
Get contents of static instance file and save to local temp file
'''
data= self.proxy.getFileContents(self.processId)
self.tmpFile.write(data.tostring())
self.tmpFile.seek(0)
def __post__(self):
'''
Posts contents of local temp file to static instance file
'''
self.tmpFile.seek(0)
data= self.tmpFile.read()
self.proxy.setFileContents(self.processId, data)
self.tmpFile.seek(0)
def getName(self):
return self.processId
def getLocalName(self):
return self.tmpFile.name
def write(self, data):
'''
Writes data to local tempfile
'''
if 'w' not in self.mode:
raise Exception('file open for read only')
self.tmpFile.write(dumps(data))
def read(self, size= -1):
'''
Reads data from local tempfile. See file read() for more details.
'''
if 'r' not in self.mode:
raise Exception('file open for write only')
return loads(self.tmpFile.read(size))
def readlines(self):
'''
Reads lines from local tempfile. See file readlines() for more detals.
'''
if 'r' not in self.mode:
raise Exception('file open for write only')
return loads(self.tmpFile.readlines())
def readline(self):
'''
Reads line from local tempfile. See file readline() for more details.
'''
if 'r' not in self.mode:
raise Exception('file open for write only')
return loads(self.tmpFile.readline())
def close(self, delete= False):
'''
Saves the contents of the local tempfile and then closes/destroys the local tempfile. See self.__post__() and python tempfile for more details.
'''
if 'w' in self.mode:
self.__post__()
elif 'r' in self.mode:
# if delete requested -- remove file form static instance
if delete:
self.proxy.deleteFile(self.processId)
self.tmpFile.close()
示例11: test_memory
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def test_memory(self):
"""
Memory test
"""
def cleanup(supress=False):
""" cleanup """
logging.debug("test_memory: Cleanup")
err = ""
if item.rm_cgroup(pwd):
err += "\nCan't remove cgroup directory"
utils.system("swapon -a")
if err:
if supress:
logging.warn("Some parts of cleanup failed%s", err)
else:
raise error.TestFail("Some parts of cleanup failed%s" % err)
# Preparation
item = CG('memory', self._client)
item.initialize(self.modules)
item.smoke_test()
pwd = item.mk_cgroup()
logging.debug("test_memory: Memory filling test")
meminfo = open('/proc/meminfo','r')
mem = meminfo.readline()
while not mem.startswith("MemFree"):
mem = meminfo.readline()
# Use only 1G or max of the free memory
mem = min(int(mem.split()[1])/1024, 1024)
mem = max(mem, 100) # at least 100M
try:
memsw_limit_bytes = item.get_property("memory.memsw.limit_in_bytes")
except error.TestFail:
# Doesn't support memsw limitation -> disabling
logging.info("System does not support 'memsw'")
utils.system("swapoff -a")
memsw = False
else:
# Supports memsw
memsw = True
# Clear swap
utils.system("swapoff -a")
utils.system("swapon -a")
meminfo.seek(0)
swap = meminfo.readline()
while not swap.startswith("SwapTotal"):
swap = meminfo.readline()
swap = int(swap.split()[1])/1024
if swap < mem / 2:
logging.error("Not enough swap memory to test 'memsw'")
memsw = False
meminfo.close()
outf = NamedTemporaryFile('w+', prefix="cgroup_client-",
dir="/tmp")
logging.debug("test_memory: Initializition passed")
################################################
# Fill the memory without cgroup limitation
# Should pass
################################################
logging.debug("test_memory: Memfill WO cgroup")
ps = item.test("memfill %d %s" % (mem, outf.name))
ps.stdin.write('\n')
i = 0
while ps.poll() == None:
if i > 60:
break
i += 1
time.sleep(1)
if i > 60:
ps.terminate()
raise error.TestFail("Memory filling failed (WO cgroup)")
outf.seek(0)
outf.flush()
out = outf.readlines()
if (len(out) < 2) or (ps.poll() != 0):
raise error.TestFail("Process failed (WO cgroup); output:\n%s"
"\nReturn: %d" % (out, ps.poll()))
if not out[-1].startswith("PASS"):
raise error.TestFail("Unsuccessful memory filling "
"(WO cgroup)")
logging.debug("test_memory: Memfill WO cgroup passed")
################################################
# Fill the memory with 1/2 memory limit
# memsw: should swap out part of the process and pass
# WO memsw: should fail (SIGKILL)
################################################
logging.debug("test_memory: Memfill mem only limit")
ps = item.test("memfill %d %s" % (mem, outf.name))
item.set_cgroup(ps.pid, pwd)
item.set_property_h("memory.limit_in_bytes", ("%dM" % (mem/2)), pwd)
ps.stdin.write('\n')
i = 0
while ps.poll() == None:
if i > 120:
break
#.........这里部分代码省略.........
示例12: History
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
class History(TestCase):
def setUp(self):
from kamaki.cli.history import History as HClass
self.HCLASS = HClass
self.file = NamedTemporaryFile()
def tearDown(self):
self.file.close()
def test__match(self):
self.assertRaises(AttributeError, self.HCLASS._match, 'ok', 42)
self.assertRaises(TypeError, self.HCLASS._match, 2.71, 'ok')
for args, expected in (
(('XXX', None), True),
((None, None), True),
(('this line has some terms', 'some terms'), True),
(('this line has some terms', 'some bad terms'), False),
(('small line', 'not so small line terms'), False),
((['line', 'with', 'some', 'terms'], 'some terms'), True),
((['line', 'with', 'some terms'], 'some terms'), False)):
self.assertEqual(self.HCLASS._match(*args), expected)
def test_add(self):
history = self.HCLASS(self.file.name)
some_strings = ('a brick', 'two bricks', 'another brick', 'A wall!')
for i, line in enumerate(some_strings):
history.add(line)
self.file.seek(0)
self.assertEqual(
self.file.read(), '\n'.join(some_strings[:(i + 1)]) + '\n')
def test_empty(self):
content = 'a brick\ntwo bricks\nanother brick\nA wall!\n'
self.file.write(content)
self.file.flush()
self.file.seek(0)
self.assertEqual(self.file.read(), content)
history = self.HCLASS(self.file.name)
history.empty()
self.file.seek(0)
self.assertEqual(self.file.read(), '0\n')
def test_retrieve(self):
sample_history = (
'0\n',
'kamaki history show\n',
'kamaki file list\n',
'kamaki file create /pithos/f1\n',
'kamaki file info /pithos/f1\n',
'last command is always excluded')
self.file.write(''.join(sample_history))
self.file.flush()
history = self.HCLASS(self.file.name)
self.assertRaises(ValueError, history.retrieve, 'must be number')
self.assertRaises(TypeError, history.retrieve, [1, 2, 3])
for i in (0, len(sample_history) + 1, - len(sample_history) - 1):
self.assertEqual(history.retrieve(i), None)
for i in range(1, len(sample_history)):
self.assertEqual(history.retrieve(i), sample_history[i])
self.assertEqual(history.retrieve(- i), sample_history[- i])
def test_limit(self):
sample_history = (
'0\n',
'kamaki history show\n',
'kamaki file list\n',
'kamaki file create /pithos/f1\n',
'kamaki file info /pithos/f1\n',
'last command is always excluded')
sample_len = len(sample_history)
self.file.write(''.join(sample_history))
self.file.flush()
history = self.HCLASS(self.file.name)
for value, exp_e in (
(-2, ValueError),
('non int', ValueError),
(None, TypeError)):
try:
history.limit = value
except Exception as e:
self.assertTrue(isinstance(e, exp_e))
history.limit = 10
self.assertEqual(history.limit, 10)
self.file.seek(0)
self.assertEqual(len(self.file.readlines()), sample_len)
history.limit = sample_len - 1
self.assertEqual(history.limit, sample_len - 1)
self.file.seek(0)
self.assertEqual(len(self.file.readlines()), sample_len)
示例13: BasicTranscludeTests
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
class BasicTranscludeTests(unittest.TestCase):
def setUp(self):
"""Create tempfile as target, add cleanup methods to close and unlink tempfiles."""
self.target = NamedTemporaryFile(delete=False)
self.addCleanup(self.target.close)
self.addCleanup(os.unlink, self.target.name)
def compare_results(self, correct_path):
"""Compare the actual result with the correct result."""
with file(correct_path, 'r+') as correct:
c = correct.readlines()
self.target.seek(0)
t = self.target.readlines()
self.assertEqual(c, t)
def test_no_transclusion(self):
"""Transcluding a file without transclude directive returns the original file."""
transclude_file(make_path("simple-test-result.md"), self.target, 'md')
self.compare_results(make_path("simple-test-result.md"))
def test_simple_transclude(self):
"""Transclude replaces directive {{some_other_file.txt}} with contents of some_other_file.txt."""
"""transclude looks for files in parent folder of source"""
transclude_file(make_path("simple-transclusion.md"), self.target, 'md')
self.compare_results(make_path("simple-test-result.md"))
def test_recursive_transclude(self):
"""Transclude is recursive."""
transclude_file(
make_path("recursive-transclusion.md"), self.target, 'md')
self.compare_results(make_path("simple-test-result.md"))
def test_two_transclusions_in_one_line(self):
"""Two transclusion directives in one file are handled correctly."""
transclude_file(make_path("double-transclusion.md"), self.target, 'md')
self.compare_results(make_path("simple-test-result.md"))
def test_wildcard_transclusion(self):
"""Wildcard transclusion {{foo.*}} wildcard is set according to type (tex, html, )"""
transclude_file(
make_path("wildcard-transclusion.md"), self.target, 'html')
self.compare_results(make_path("simple-test-result.md"))
def test_missing_file_raises_error(self):
"""transclude outputs an error when a file to transclude is not found."""
self.assertRaises(MissingFileException,
transclude_file,
make_path("missing-transclusion.md"),
self.target,
'md')
def test_transclude_base(self):
"""If metadata "Transclude Base" is set, transclude looks there for files."""
"""metadata "Transclude Base" is only evaluated in the first file."""
transclude_file(
make_path("new-transclude-base.md"), self.target, 'html')
self.compare_results(make_path("new-transclude-base-result.md"))
def test_recursion_nested_folders(self):
"""Transclude ignores metadata in transculded file."""
"""with recursion, transclude looks for files relative to the file which transludes them."""
"""after recursion, transclude looks for files again relative to source."""
"""metadata of recursed files is ignored in result."""
"""metadata of source file is included in result"""
# TODO: split into smaller tests
transclude_file(
make_path("recursive-subfolder.md"), self.target, 'html')
self.compare_results(make_path("recursive-subfolder-result.md"))
示例14: main
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
def main(argv):
# configuration vars
RUN_PERIOD = "RunPeriod-2014-10"
CONDITION_FILE_FORMAT = "/work/halld/online_monitoring/conditions/run_conditions%06d.dat"
# assume that the files are loaded on the cache disk
RAWDATA_DIR_FORMAT = "/cache/mss/halld/RunPeriod-2014-10/rawdata/Run%06d"
# read in run number from command line
try:
run_number = int(argv[0])
except:
print "Need to pass the run number to process as a command line argument!"
return
run_properties = init_property_mapping()
run_conditions = parse_condition_file(CONDITION_FILE_FORMAT % (run_number))
if run_conditions is None:
return
# start extracting saved EPICS values
# run_number = run_conditions['RUN'] ## check this?
run_properties["beam_current"] = run_conditions["IBCAD00CRCUR6"]
run_properties["start_time"] = run_conditions["TIME"]
run_properties["solenoid_current"] = run_conditions["HallD-PXI:Data:I_Shunt"]
# figure out which radiator was used
# save luminosity factor = current * radiator thickness
amorphous_radiator_position = float(run_conditions["hd:radiator:motor.RBV"])
if fabs(amorphous_radiator_position - 135.948) < RADIATOR_TOLERANCE:
run_properties["radiator_type"] = "2x10-5 RL"
run_properties["luminosity"] = 1.7e-5 * float(run_properties["beam_current"])
elif fabs(amorphous_radiator_position - 166.095) < RADIATOR_TOLERANCE:
run_properties["radiator_type"] = "1x10-4 RL"
run_properties["luminosity"] = 11.2e-5 * float(run_properties["beam_current"])
elif fabs(amorphous_radiator_position - 196.262) < RADIATOR_TOLERANCE:
run_properties["radiator_type"] = "3x10-4 RL"
run_properties["luminosity"] = 22.7e-5 * float(run_properties["beam_current"])
else:
run_properties["radiator_type"] = "None"
# run_properties['luminosity'] = run_properties['beam_current']
run_properties["luminosity"] = 0.0
# parse EVIO files to extract useful information
# eventually the DAQ will report this properly?
rawdata_evio_dir = RAWDATA_DIR_FORMAT % (run_number)
if os.path.isdir(rawdata_evio_dir):
filelist = [
join(rawdata_evio_dir, f)
for f in listdir(rawdata_evio_dir)
if ((f[:10] == "hd_rawdata" or f[:6] == "hd_raw") and (f[-5:] == ".evio"))
]
filelist.sort()
file_properties = ParseEVIOFiles(filelist)
if len(file_properties) > 0:
run_properties["num_events"] = file_properties["num_events"]
run_properties["num_files"] = file_properties["num_files"]
run_properties["start_time"] = file_properties["start_time"]
run_properties["end_time"] = file_properties["end_time"]
# pull out target information from the CCDB
# load CCDB connection
ccdb_context = InitCCDB()
# read target index -> name mapping definition in from the CCDB
target_types = load_target_types(ccdb_context, run_number)
# make temp file to store CCDB info in
fconst = NamedTemporaryFile()
ccdb_context.process_command_line("dump /TARGET/target_parms:" + str(run_number) + " > " + fconst.name)
# read in info
fconst.flush()
const_lines = fconst.readlines()
if len(const_lines) < 2:
print "Problem writing out CCDB constants to file!"
else:
# the first line of the output file from CCDB is junk, and our numbers are on the second line
vals = const_lines[1].split()
target_index = int(vals[0])
if target_index in target_types:
run_properties["target_type"] = target_types[target_index]
else:
print "Invalid target index from CCDB = " + str(target_index)
fconst.close()
if VERBOSE:
print "RUN PROPERTIES FOR RUN " + str(run_number)
print str(run_properties)
# Add information to DB
## initialize DB
db = datamon_db()
## add blank run to DB if it doesn't exist
if db.GetRunID(run_number) < 0:
db.CreateRun(run_number)
db.UpdateRunInfo(run_number, run_properties)
示例15: __init__
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import readlines [as 别名]
class _FileLogger:
"""File logging class wrapper.
Class wrapping is needed manly for safety of log file removal
after Blender is shut down.
Registering fuction for atexit module makes sure than,
file is deleted if Blender is closed normally.
However file is not deleted if process is killed in Linux.
On Windows, on the other hand, file gets deleted even if Blender
is closed from Task Manager -> End Task/Process
"""
__log_file = None
def __init__(self):
self.__log_file = NamedTemporaryFile(mode="w+", suffix=".log.txt", delete=True)
# instead of destructor we are using delete method,
# to close and consequentially delete log file
atexit.register(self.delete)
def delete(self):
"""Closes file and consiquentally deletes it as log file was created in that fashion.
"""
# close file only if it's still exists in class variable
if self.__log_file is not None:
self.__log_file.close()
self.__log_file = None
def write(self, msg_object):
"""Writes message to the log file.
:param msg_object: message to be written to file
:type msg_object: object
"""
self.__log_file.write(msg_object)
def flush(self):
"""Flushes written content to file on disk."""
self.__log_file.flush()
def get_log(self):
"""Gets current content of temporary SCS BT log file,
which was created at startup and is having log of BT session.
:return: current content of log file as string
:rtype: str
"""
# firstly move to start of the file
self.__log_file.seek(0)
log = ""
for line in self.__log_file.readlines():
log += line.replace("\t ", "\t\t ") # replace for Blender text editor to be aligned the same as in console
return log