本文整理汇总了Python中tempfile.TemporaryFile.readlines方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryFile.readlines方法的具体用法?Python TemporaryFile.readlines怎么用?Python TemporaryFile.readlines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.TemporaryFile
的用法示例。
在下文中一共展示了TemporaryFile.readlines方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_request
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def handle_request(request, object_id, size=None):
book = get_object_or_404(Book, pk=object_id)
if size is None:
size = request.REQUEST.get('size',None)
handle_number = book.identifier.split(':')[2].replace('/', '_')
file_name_complete = 'var/media/' + handle_number + '_' + size + '.pdf'
file_name_inprogress = 'var/media/' + handle_number + '_' + size
if os.path.exists(file_name_complete):
print "found complete PDF"
PDF_file = open(file_name_complete, 'r')
return HttpResponse(File(PDF_file).readlines(), mimetype='application/pdf')
elif os.path.exists(file_name_inprogress):
print "found PDF in progress"
tempfile = TemporaryFile()
tempfile.write('PDF compilation in progress, please check back later...')
tempfile.seek(0);
return HttpResponse(tempfile.readlines(), mimetype='text/plain')
else:
# Fire the missiles
f = open(file_name_inprogress, 'w')
PDF_file = File(f)
t = threading.Thread(target=compile_PDF,
args=[request, book, PDF_file, size])
t.setDaemon(True)
t.start()
tempfile = TemporaryFile()
tempfile.write('PDF compilation initiated, please check back later...')
tempfile.seek(0);
return HttpResponse(tempfile.readlines(), mimetype='text/plain')
示例2: _add_hostname_to_hosts
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def _add_hostname_to_hosts():
"""Adds the hostname to /etc/hosts, if it is not being assigned by DNS -- required for rabbitmq
"""
hostname_file = open('/etc/hostname','r')
hostname = hostname_file.readline().rstrip()
private_ip = _get_self_private_ip()
host_found = _check_name_resolves(hostname)
if not host_found:
stdout = TemporaryFile()
stderr = TemporaryFile()
err = subprocess.call( ('/usr/bin/sudo','/usr/bin/perl', '-i.orig', '-n','-e', r"""BEGIN {($h,$ip)[email protected];
$ip='127.0.1.1' unless $ip
}
next if/\Q$h\E/;
s/^(127\.0\.0\.1\s+localhost)$/$1\n$ip $h/;
print""", hostname, private_ip, '/etc/hosts'),
stdout=stdout, stderr=stderr)
if err:
stdout.seek(0)
out='\n'.join(stdout.readlines())
stderr.seek(0)
err_text='\n'.join(stderr.readlines())
raise OSError('Error updating /etc/hosts. Result code: {0}\n{1}\n{2}'.format( err,out,err_text ))
stdout.close()
stderr.close()
示例3: execute_local
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def execute_local(args, env = {}):
"""
Execute a command locally. This method is a wrapper for
:py:class:`subprocess.Popen` with stdout and stderr piped to
temporary files and ``shell=True``.
:param str args: command with arguments (e.g. 'sbatch myjob.sh')
:param dict env: environment variables (default: {})
:return: object with attributes ``stdout``, ``stderr`` \
and ``returncode``
:rtype: :py:obj:`object`
"""
from tempfile import TemporaryFile
from subprocess import Popen
# Note: PIPE will cause deadlock if output is larger than 65K
stdout, stderr = TemporaryFile(), TemporaryFile()
handle = type('Handle', (object,), {'stdout' : [], 'stderr' : [], 'returncode' : 0})()
p = Popen(args, stdout = stdout, stderr = stderr, env = env, shell = True)
p.wait()
handle.stdout = stdout.seek(0) or stdout.readlines()
handle.stderr = stderr.seek(0) or stderr.readlines()
handle.returncode = p.returncode
return handle
示例4: _process_data_1
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def _process_data_1(self, cr, uid, ids, data, context):
#try:
fileobj = TemporaryFile('w+')
fileobj.write(data)
fileobj.seek(0)
lines = []
for line in fileobj.readlines():
#log.info('++++++++++++++++\r\nline=%s' % line)
lines = line.split(',')
#if len(lines) == 0: break
if self._isnumeric(lines[0]) == True:
id = int(lines[0])
date_from = datetime.strptime(lines[1], '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
date_to = datetime.strptime(lines[2].replace("\n",""), '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
#log.info('id=%s,df=%s,dt=%s' % (id, date_from, date_to))
#check existing
day = datetime.strptime(date_from, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
attds = self.pool.get('hr.attendance')
attd_ids = attds.search(cr, uid, [('employee_id','=',id),('day','=',day)], context=context)
#log.info(attd_ids)
log.info('employee_id=%d,attd_ids=%s,len=%d,day=%s' % (id,attd_ids,len(attd_ids), day))
if len(attd_ids) == 0:
attds.create(cr, uid, {'employee_id':id,'name':date_from,'action':'sign_in','source':'import'})
attds.create(cr, uid, {'employee_id':id,'name':date_to,'action':'sign_out','source':'import'})
#log.info('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
fileobj.close()
示例5: BuildTests
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
class BuildTests(unittest.TestCase):
def setUp(self):
self.fnull = TemporaryFile()
def tearDown(self):
self._run(["./waf","distclean"])
self.fnull.close()
def _run(self, args):
sub = subprocess.Popen(args, stderr=self.fnull, stdout=self.fnull)
sub.communicate()
self.fnull.seek(0)
tail = ''.join(self.fnull.readlines()[-10:])
return sub, tail
def _configure(self, gtk, backend, delint):
arglist = ["./waf","configure","--gtk", gtk, "--backend", backend]
if delint:
arglist.append("--enable-delint")
sub, tail = self._run(arglist)
self.assertEqual(0, sub.returncode, msg=tail)
def _build(self):
sub, tail = self._run(["./waf","build"])
self.assertEqual(0, sub.returncode, msg=tail)
def _configure_and_build(self, gtk, backend, delint):
self._configure(gtk, backend, delint)
self._build()
示例6: check_commit_id
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def check_commit_id(path):
cur_dir = os.getcwd()
commit = None
stderr = TemporaryFile()
try:
os.chdir(path)
git_cmd = 'git log -1 --format="%H" | cut -c1-32'
git_out = Popen(git_cmd,
shell=True,
stdin=PIPE,
stdout=PIPE,
stderr=stderr,
close_fds=True)
errmsg = stderr.readlines()
if errmsg:
logging.debug("git error message (in %s): %s" % (path, '\n'.join(errmsg)))
try:
commit = git_out.stdout.readlines()[0].strip()
except IndexError:
pass
finally:
os.chdir(cur_dir)
stderr.close()
return commit
示例7: local_ds_files
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def local_ds_files(ds):
"""
Gets the list of files corresponding to a published dataset
stored on cms_dbs_ph_analysis_02.
Args:
ds: the path to the published dataset, ending in /USER
Returns:
A list of the LFN-s of the dataset.
"""
tf = TemporaryFile()
stdout = sys.stdout
stdout.flush()
sys.stdout = tf
print "Query"
ret = call_das_cli('--query=file dataset=%s instance=cms_dbs_ph_analysis_02' % ds, '--limit=0')
print ret
tf.flush()
tf.seek(0)
sys.stdout = stdout
fl = []
for li in tf.readlines():
if "/store/" in li:
fl.append(li.strip())
tf.close()
return fl
示例8: test_open_in_binary
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def test_open_in_binary(self):
outfile = TemporaryFile('wb+')
g = self.getGClass()(outfile=outfile, print_lines=False)
g.move(10,10)
outfile.seek(0)
lines = outfile.readlines()
assert(type(lines[0]) == bytes)
outfile.close()
示例9: process_qif
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def process_qif(self, cr, uid, data_file, journal_id=False, context=None):
""" Import a file in the .QIF format"""
try:
fileobj = TemporaryFile('wb+')
fileobj.write(base64.b64decode(data_file))
fileobj.seek(0)
file_data = ""
for line in fileobj.readlines():
file_data += line
fileobj.close()
if '\r' in file_data:
data_list = file_data.split('\r')
else:
data_list = file_data.split('\n')
header = data_list[0].strip()
header = header.split(":")[1]
except:
raise osv.except_osv(_('Import Error!'), _('Please check QIF file format is proper or not.'))
line_ids = []
vals_line = {}
total = 0
if header == "Bank":
vals_bank_statement = {}
for line in data_list:
line = line.strip()
if not line:
continue
if line[0] == 'D': # date of transaction
vals_line['date'] = dateutil.parser.parse(line[1:], fuzzy=True).date()
if vals_line.get('date') and not vals_bank_statement.get('period_id'):
period_ids = self.pool.get('account.period').find(cr, uid, vals_line['date'], context=context)
vals_bank_statement.update({'period_id': period_ids and period_ids[0] or False})
elif line[0] == 'T': # Total amount
total += float(line[1:].replace(',', ''))
vals_line['amount'] = float(line[1:].replace(',', ''))
elif line[0] == 'N': # Check number
vals_line['ref'] = line[1:]
elif line[0] == 'P': # Payee
bank_account_id, partner_id = self._detect_partner(cr, uid, line[1:], identifying_field='owner_name', context=context)
vals_line['partner_id'] = partner_id
vals_line['bank_account_id'] = bank_account_id
vals_line['name'] = 'name' in vals_line and line[1:] + ': ' + vals_line['name'] or line[1:]
elif line[0] == 'M': # Memo
vals_line['name'] = 'name' in vals_line and vals_line['name'] + ': ' + line[1:] or line[1:]
elif line[0] == '^': # end of item
line_ids.append((0, 0, vals_line))
vals_line = {}
elif line[0] == '\n':
line_ids = []
else:
pass
else:
raise osv.except_osv(_('Error!'), _('Cannot support this Format !Type:%s.') % (header,))
vals_bank_statement.update({'balance_end_real': total,
'line_ids': line_ids,
'journal_id': journal_id})
return [vals_bank_statement]
示例10: run
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def run(self):
tmpfile = TemporaryFile()
shell = Shell(stdout=tmpfile)
try:
shell.runcmd(self.cmd)
shell.end(0, exception=False)
except Exception as e:
shell.print(str(e) + "\n")
tmpfile.seek(0)
self.stdout = [x.decode("utf-8") for x in tmpfile.readlines()]
tmpfile.close()
示例11: get
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def get(self,x=0):
if(ImgHandler.img==None):
return
#print ImgHandler.img
tempFile = TemporaryFile()
ImgHandler.img.save(tempFile)
tempFile.seek(0)
lines = tempFile.readlines()
#print len(lines)
self.output = ''.join(lines)
self.set_header("Cache-control", "no-cache")
self.set_header("Content-Type","image/png")
self.set_header("Content-Length",len(self.output))
self.write(self.output)
self.finish()
示例12: FilePrinterTest
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
class FilePrinterTest(unittest.TestCase):
def test_invalid_construction(self):
self.assertRaises(TypeError, FilePrinter, 5)
def test_printing(self):
self.file = TemporaryFile("w+")
self.uut = FilePrinter(self.file)
self.uut.print("Test value")
self.uut = FilePrinter(self.file)
self.uut.print("Test", "value2")
self.file.seek(0)
lines = self.file.readlines()
self.assertEqual(lines, ["Test value\n", "Test value2\n"])
示例13: TestGFixture
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
class TestGFixture(unittest.TestCase):
def getGClass(self):
return G
def setUp(self):
self.outfile = TemporaryFile('w+')
self.g = self.getGClass()(outfile=self.outfile, print_lines=False,
aerotech_include=False)
self.expected = ""
if self.g.is_relative:
self.expect_cmd('G91 ;relative')
else:
self.expect_cmd('G90 ;absolute')
def tearDown(self):
self.g.teardown()
del self.outfile
del self.g
# helper functions #######################################################
def expect_cmd(self, cmd):
self.expected = self.expected + cmd + '\n'
def assert_output(self):
string_rep = ""
if is_str(self.expected):
string_rep = self.expected
self.expected = self.expected.split('\n')
self.expected = [x.strip() for x in self.expected if x.strip()]
self.outfile.seek(0)
lines = self.outfile.readlines()
if 'b' in self.outfile.mode:
lines = [decode2To3(x) for x in lines]
lines = [x.strip() for x in lines if x.strip()]
self.assertListEqual(lines, self.expected)
self.expected = string_rep
def assert_almost_position(self, expected_pos):
for k, v in expected_pos.items():
self.assertAlmostEqual(self.g.current_position[k], v)
def assert_position(self, expected_pos):
self.assertEqual(self.g.current_position, expected_pos)
示例14: get_directories
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
def get_directories(start_dir, find_command):
"""
Runs a find command and returns a list of directories, checks
output for sanity (whether it really is an existing directory).
"""
def print_logs(stdout, stderr):
stdout.seek(0) # move pointer back to beginning before read()
stderr.seek(0)
delim = 78 * '-'
print("%s\nstdout:\n%s\n%s\nstderr:\n%s\n%s" % (delim, stdout.read(),
delim, stderr.read(), delim))
print("Running command '%s' ..." % find_command)
stdout, stderr = TemporaryFile("w+"), TemporaryFile("w+")
try:
proc = subprocess.Popen(find_command.split(),
stdout=stdout, stderr=stderr)
except Exception as ex:
print("Exception occured when executing the command, reason: %s" % ex)
sys.exit(1)
try:
returncode = proc.wait()
except Exception as ex:
print("Exception occured (logs below), reason: %s" % ex)
print_logs(stdout, stderr)
sys.exit(1)
if returncode == 0:
print("Command finished.")
stdout.seek(0) # move pointer back to beginning before read()
# assuming each line of in the output is a returned directory name
dirs = [d.strip().replace("./", "") for d in stdout.readlines() \
if os.path.exists(d.strip())]
return dirs
else:
print("Command '%s' failed, return code: %s" % (find_command,
returncode))
print_logs(stdout, stderr)
sys.exit(1)
示例15: Devlin
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import readlines [as 别名]
class CapturedStdout:
"""Capture sys.out output in temp file to allow function result testing
Thanks to Catherine Devlin (catherinedevlin.blogspot.com) for the idea"""
def __init__(self):
"""Capture stdout"""
self.backupStdout=sys.stdout
self.tmpFile=TemporaryFile()
sys.stdout=self.tmpFile
def readlines(self, reset=True):
"""
@param reset: reset buffer for next usage (default is True)
@return: array of lines captured and reset buffer"""
self.tmpFile.seek(0)
lines=self.tmpFile.readlines()
if reset:
self.reset()
return [line.strip("\n").strip("\x00") for line in lines]
def reset(self):
"""Reset stdout buffer"""
self.tmpFile.truncate(0)
def gotPsyqlException(self, reset=True):
"""Look if captured output has a PysqlException
@param reset: reset buffer for next usage (default is True)
@return: True is got exception, else False"""
lines=self.readlines(reset)
for line in lines:
if "Pysql error" in line:
return True
return False
def echoStdout(self):
"""Echo the current buffer on terminal stdout. Usefull for test debuging"""
self.backupStdout.writelines(["%s\n" % line for line in self.readlines(reset=False)])
def restoreStdout(self):
sys.stdout=self.backupStdout
self.tmpFile.close()