本文整理汇总了Python中terminal.Terminal.write方法的典型用法代码示例。如果您正苦于以下问题:Python Terminal.write方法的具体用法?Python Terminal.write怎么用?Python Terminal.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类terminal.Terminal
的用法示例。
在下文中一共展示了Terminal.write方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_log_frames
# 需要导入模块: from terminal import Terminal [as 别名]
# 或者: from terminal.Terminal import write [as 别名]
def render_log_frames(golog_path, rows, cols, limit=None):
"""
Returns the frames of *golog_path* as a list of HTML-encoded strings that
can be used with the playback_log.html template. It accomplishes this task
by running the frames through the terminal emulator and capturing the HTML
output from the `Terminal.dump_html` method.
If *limit* is given, only return that number of frames (e.g. for preview)
"""
out_frames = []
from terminal import Terminal
term = Terminal(
# 14/7 for the em_height should be OK for most browsers to ensure that
# images don't always wind up at the bottom of the screen.
rows=rows, cols=cols, em_dimensions={'height':14, 'width':7})
for i, frame in enumerate(get_frames(golog_path)):
if limit and i == limit:
break
if len(frame) > 14:
if i == 0 and frame[14:15] == b'{':
# This is just the metadata frame. Skip it
continue
frame_time = int(float(frame[:13]))
frame_screen = frame[14:] # Skips the colon
# Emulate how a real shell would output newlines:
frame_screen = frame_screen.replace(b'\n', b'\r\n')
term.write(frame_screen)
# Ensure we're not in the middle of capturing a file. Otherwise
# it might get cut off and result in no image being shown.
if term.capture:
continue
scrollback, screen = term.dump_html()
out_frames.append({'screen': screen, 'time': frame_time})
del term # Ensures any file capture file descriptors are cleaned up
return out_frames # Skip the first frame which is the metadata
示例2: _retrieve_log_flat
# 需要导入模块: from terminal import Terminal [as 别名]
# 或者: from terminal.Terminal import write [as 别名]
def _retrieve_log_flat(queue, settings):
"""
Writes the given *log_filename* to *queue* in a flat format equivalent to::
./logviewer.py --flat log_filename
*settings* - A dict containing the *log_filename*, *colors_css*, and
*theme_css* to use when generating the HTML output.
"""
out_dict = {
'result': "",
'log': "",
'metadata': {},
}
# Local variables
out = []
spanstrip = re.compile(r'\s+\<\/span\>$')
user = settings['user']
users_dir = settings['users_dir']
log_filename = settings['log_filename']
logs_dir = os.path.join(users_dir, "logs")
log_path = os.path.join(logs_dir, log_filename)
if os.path.exists(log_path):
out_dict['metadata'] = get_or_update_metadata(log_path, user)
out_dict['metadata']['filename'] = log_filename
out_dict['result'] = "Success"
from io import BytesIO
# Use the terminal emulator to create nice HTML-formatted output
from terminal import Terminal
term = Terminal(rows=100, cols=300, em_dimensions=0)
io_obj = BytesIO()
flatten_log(log_path, io_obj)
io_obj.seek(0)
# Needed to emulate an actual term
flattened_log = io_obj.read().replace(b'\n', b'\r\n')
# NOTE: Using chunking below to emulate how a stream might actually be
# written to the terminal emulator. This is to prevent the emulator
# from thinking that any embedded files (like PDFs) are never going to
# end.
def chunker(s, n):
"""Produce `n`-character chunks from `s`."""
for start in range(0, len(s), n):
yield s[start:start+n]
for chunk in chunker(flattened_log, 499):
term.write(chunk)
scrollback, screen = term.dump_html()
# Join them together
log_lines = scrollback + screen
# rstrip the lines
log_lines = [a.rstrip() for a in log_lines]
# Fix things like "<span>whatever [lots of whitespace] </span>"
for i, line in enumerate(log_lines):
out.append(spanstrip.sub("</span>", line))
out_dict['log'] = out
term.clear_screen() # Ensure the function below works...
term.close_captured_fds() # Force clean up open file descriptors
else:
out_dict['result'] = _("ERROR: Log not found")
message = {'terminal:logging_log_flat': out_dict}
queue.put(message)
示例3: _retrieve_log_flat
# 需要导入模块: from terminal import Terminal [as 别名]
# 或者: from terminal.Terminal import write [as 别名]
def _retrieve_log_flat(queue, settings):
"""
Writes the given *log_filename* to *queue* in a flat format equivalent to::
./logviewer.py --flat log_filename
*settings* - A dict containing the *log_filename*, *colors*, and *theme* to
use when generating the HTML output.
"""
out_dict = {
'result': "",
'log': "",
'metadata': {},
}
# Local variables
out = []
spanstrip = re.compile(r'\s+\<\/span\>$')
gateone_dir = settings['gateone_dir']
user = settings['user']
users_dir = settings['users_dir']
container = settings['container']
prefix = settings['prefix']
log_filename = settings['log_filename']
theme = "%s.css" % settings['theme']
colors = "%s.css" % settings['colors']
logs_dir = os.path.join(users_dir, "logs")
log_path = os.path.join(logs_dir, log_filename)
if os.path.exists(log_path):
out_dict['metadata'] = get_or_update_metadata(log_path, user)
out_dict['metadata']['filename'] = log_filename
out_dict['result'] = "Success"
import StringIO
# Use the terminal emulator to create nice HTML-formatted output
from terminal import Terminal
term = Terminal(rows=100, cols=300)
io_obj = StringIO.StringIO()
flatten_log(log_path, io_obj)
io_obj.seek(0)
# Needed to emulate an actual term
flattened_log = io_obj.read().replace('\n', '\r\n')
term.write(flattened_log)
scrollback, screen = term.dump_html()
# Join them together
log_lines = scrollback + screen
# rstrip the lines
log_lines = [a.rstrip() for a in log_lines]
# Fix things like "<span>whatever [lots of whitespace] </span>"
for i, line in enumerate(log_lines):
out.append(spanstrip.sub("</span>", line))
out_dict['log'] = out
else:
out_dict['result'] = _("ERROR: Log not found")
message = {'logging_log_flat': out_dict}
queue.put(message)
示例4: flatten_log
# 需要导入模块: from terminal import Terminal [as 别名]
# 或者: from terminal.Terminal import write [as 别名]
def flatten_log(log_path, file_like, preserve_renditions=True, show_esc=False):
"""
Given a log file at *log_path*, write a string of log lines contained
within to *file_like*. Where *file_like* is expected to be any file-like
object with write() and flush() methods.
If *preserve_renditions* is True, CSI escape sequences for renditions will
be preserved as-is (e.g. font color, background, etc). This is to make the
output appear as close to how it was originally displayed as possible.
Besides that, it looks really nice =)
If *show_esc* is True, escape sequences and control characters will be
visible in the output. Trailing whitespace and escape sequences will not be
removed.
..note::
Converts our standard recording-based log format into something that
can be used with grep and similar search/filter tools.
"""
from terminal import Terminal, SPECIAL
metadata = get_log_metadata(log_path)
rows = metadata.get('rows', 24)
cols = metadata.get('columns', None)
if not cols:
# Try the old metadata format which used 'cols':
cols = metadata.get('cols', 80)
term = Terminal(rows=rows, cols=cols, em_dimensions=0)
out_line = u""
cr = False
# We skip the first frame, [1:] because it holds the recording metadata
for count, frame in enumerate(get_frames(log_path)):
if count == 0:
# Skip the first frame (it's just JSON-encoded metadata)
continue
# First 13 chars is the timestamp:
frame_time = float(frame.decode('UTF-8', 'ignore')[:13])
# Convert to datetime object
frame_time = datetime.fromtimestamp(frame_time/1000)
if show_esc:
frame_time = frame_time.strftime(u'\x1b[0m%b %m %H:%M:%S')
else: # Renditions preserved == I want pretty. Make the date bold:
frame_time = frame_time.strftime(u'\x1b[0;1m%b %m %H:%M:%S\x1b[m')
if not show_esc:
term.write(frame[14:])
if term.capture:
# Capturing a file... Keep feeding it frames until complete
continue
elif term.captured_files:
for line in term.screen:
# Find all the characters that come before/after the capture
for char in line:
if ord(char) >= SPECIAL:
adjusted = escape_escape_seq(out_line, rstrip=True)
adjusted = frame_time + u' %s\n' % adjusted
file_like.write(adjusted.encode('utf-8'))
out_line = u""
if char in term.captured_files:
captured_file = term.captured_files[char].file_obj
captured_file.seek(0)
file_like.write(captured_file.read())
file_like.write(b'\n')
del captured_file
term.clear_screen()
term.close_captured_fds() # Instant cleanup
else:
out_line += char
if not out_line:
continue
adjusted = frame_time + u' %s\n' % out_line.strip()
file_like.write(adjusted.encode('utf-8'))
out_line = u""
continue
else:
term.clear_screen()
frame = frame.decode('UTF-8', 'ignore')
for char in frame[14:]:
if '\x1b[H\x1b[2J' in out_line: # Clear screen sequence
# Handle the clear screen (usually ctrl-l) by outputting
# a new log entry line to avoid confusion regarding what
# happened at this time.
out_line += u"^L" # Clear screen is a ctrl-l or equivalent
if show_esc:
adjusted = raw(out_line)
else:
adjusted = escape_escape_seq(out_line, rstrip=True)
adjusted = frame_time + u' %s\n' % adjusted
file_like.write(adjusted.encode('utf-8'))
out_line = u""
continue
if char == u'\n':
if show_esc:
adjusted = raw(out_line)
else:
adjusted = escape_escape_seq(out_line, rstrip=True)
if not adjusted:
out_line = u"" # Skip empty lines
continue
adjusted = frame_time + u' %s\n' % adjusted
file_like.write(adjusted.encode('utf-8'))
#.........这里部分代码省略.........
示例5: submit
# 需要导入模块: from terminal import Terminal [as 别名]
# 或者: from terminal.Terminal import write [as 别名]
def submit(self, jobInfo_, logdir=""):
self.log("Submitting job ", jobInfo_.name)
if not logdir:
logdir = self._workspace + "/logs"
try:
if jobInfo_.cluster == "lsf":
command = "bsub -J {jobName} -o {log} -cwd '$TMPDIR' {options} 'source {environment};darun.py {workspace} {jobName} {key}'".format(
jobName=jobInfo_.name,
log=logdir + "/" + jobInfo_.name + ".log",
options=self.options["lsf"],
environment=self._workspace + "/environment",
workspace=self._workspace,
key=jobInfo_.key,
)
self.log(command)
bsubout = self._terminal.communicate(command)
success = False
if len(bsubout) != 0 and "submitted" in bsubout[0]:
matches = re.search("<([0-9]+)>", bsubout[0])
if matches:
success = True
if not success:
self.log("bsub failed")
raise Exception
self.log("lxbatch job ID for {0} is {1}".format(jobInfo_.name, matches.group(1)))
proc = matches.group(1)
node = ""
elif jobInfo_.cluster == "interactive":
node = TERMNODE
if LOADBALANCE:
hostProc = subprocess.Popen(["host", TERMNODE], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = hostProc.communicate()
for line in out.split("\n"):
if "has address" in line:
addr = line.split()[3]
for term in Terminal.OPENTERMS:
if term.addr == addr:
break
else:
node = addr
break
command = "cd $TMPDIR;source {environment};darun.py -p {workspace} {jobName} {key} >> {log} 2>&1;exit".format(
environment=self._workspace + "/environment",
workspace=self._workspace,
jobName=jobInfo_.name,
key=jobInfo_.key,
log=logdir + "/" + jobInfo_.name + ".log",
)
self.log(node + ":", command)
term = Terminal(node)
term.write(command)
self.log("Command issued to", term.node)
proc = term
node = term.node
elif jobInfo_.cluster == "local":
command = "cd {tmpdir};source {environment};darun.py -p {workspace} {jobName} {key} >> {log} 2>&1".format(
tmpdir=TMPDIR,
environment=self._workspace + "/environment",
workspace=self._workspace,
jobName=jobInfo_.name,
key=jobInfo_.key,
log=logdir + "/" + jobInfo_.name + ".log",
)
self.log(command)
proc = subprocess.Popen(
command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
) # stdout will be redirected to a log file within the job
self.log("Subprocess started")
node = "localhost"
except:
return False
with self._lock:
jobInfo_.proc = proc
jobInfo_.state = "PENDING"
jobInfo_.node = node
jobInfo_.lastHB = time.time()
self._stateChanged.set()
#.........这里部分代码省略.........