async def _exec_tty(root: Root, job: str, exec_id: str) -> None: loop = asyncio.get_event_loop() helper = AttachHelper(quiet=True) stdout = create_output() h, w = stdout.get_size() async with root.client.jobs.exec_start(job, exec_id) as stream: try: await root.client.jobs.exec_resize(job, exec_id, w=w, h=h) except IllegalArgumentError: pass info = await root.client.jobs.exec_inspect(job, exec_id) if not info.running: # Exec session is finished sys.exit(info.exit_code) tasks = [] tasks.append(loop.create_task(_process_stdin_tty(stream, helper))) tasks.append( loop.create_task(_process_stdout_tty(root, stream, stdout, helper))) tasks.append( loop.create_task( _process_resizing( functools.partial(root.client.jobs.exec_resize, job, exec_id), stdout, ))) tasks.append(loop.create_task(_exec_watcher(root, job, exec_id))) try: await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) finally: for task in tasks: await root.cancel_with_logging(task)
def __init__(self, title: AnyFormattedText = None, formatters: Optional[Sequence[Formatter]] = None, bottom_toolbar: AnyFormattedText = None, style: Optional[BaseStyle] = None, key_bindings: Optional[KeyBindings] = None, file=None, color_depth: Optional[ColorDepth] = None, output: Optional[Output] = None, input: Optional[Input] = None) -> None: self.title = title self.formatters = formatters or create_default_formatters() self.bottom_toolbar = bottom_toolbar self.counters: List[ProgressBarCounter] = [] self.style = style self.key_bindings = key_bindings # Note that we use __stderr__ as default error output, because that # works best with `patch_stdout`. self.color_depth = color_depth self.output = output or create_output(stdout=file or sys.__stderr__) self.input = input self._thread: Optional[threading.Thread] = None self._loop = get_event_loop() self._app_loop = new_event_loop() self._previous_winch_handler = signal.getsignal(signal.SIGWINCH) self._has_sigwinch = False
def __init__(self, debug: bool = True, prompt: str = "> ") -> None: self.debug_ = debug self.prompt = ANSI("> " if prompt is None else prompt) self.stdout = StdoutProxy(sleep_between_writes=0.5) self.out = create_output(self.stdout) self.ses = PromptSession(output=self.out)
def output_stream(self, pointer): """ Sets the output stream pointer to use. :param pointer: Stream pointer number :since: v1.0.0 """ set_default_output(create_output(pointer))
async def _attach_tty(root: Root, job: str, logs: bool) -> InterruptAction: if not root.quiet: click.echo(JOB_STARTED_TTY) loop = asyncio.get_event_loop() helper = AttachHelper(quiet=root.quiet) stdout = create_output() h, w = stdout.get_size() if logs: logs_printer = loop.create_task(process_logs(root, job, helper)) else: # Placeholder, prints nothing logs_printer = loop.create_task(asyncio.sleep(0)) async with root.client.jobs.attach(job, stdin=True, stdout=True, stderr=True, logs=True) as stream: try: await root.client.jobs.resize(job, w=w, h=h) except IllegalArgumentError: # Job may be finished at this moment. # Need to check job's status and print logs # for finished job pass status = await root.client.jobs.status(job) if status.status is not JobStatus.RUNNING: # Job is finished await logs_printer if status.status == JobStatus.FAILED: sys.exit(status.history.exit_code or EX_PLATFORMERROR) else: sys.exit(status.history.exit_code) tasks = [] tasks.append(loop.create_task(_process_stdin_tty(stream, helper))) tasks.append( loop.create_task(_process_stdout_tty(root, stream, stdout, helper))) tasks.append( loop.create_task( _process_resizing( functools.partial(root.client.jobs.resize, job), stdout))) tasks.append(loop.create_task(_attach_watcher(root, job))) try: await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) finally: for task in tasks: await root.cancel_with_logging(task) await root.cancel_with_logging(logs_printer) return helper.action
def stubLaravel(userInput): appName = userInput['app']['name'] laravelVersion = userInput['app']['laravel_version'] out = create_output() myCwd = os.getcwd() if not os.path.exists(os.path.join(myCwd, appName)): subprocess.call( "composer create-project --no-install --no-dev --no-scripts laravel/laravel %s %s" % (appName, laravelVersion), shell=True, stdout=out, stderr=out, cwd=myCwd) else: print( "File or directory with given project name already exists. Stub creation skipped." ) lines = [] envExample = os.path.join(myCwd, appName, '.env.example') with open(envExample, 'r') as fh: text = fh.read() if not re.search(r"APP_URL=http://%s" % (userInput['app']['url']), text): lines.append( r"sed -i 's/APP_URL=http:\/\/localhost/APP_URL=http:\/\/%s/g' .env.example" % (userInput['app']['url'])) if not re.search(r"DB_HOST=%s-database" % (appName), text): lines.append( r"sed -i 's/DB_HOST=127.0.0.1/DB_HOST=%s-database/g' .env.example" % (appName)) if not re.search(r'DB_DATABASE=main', text): lines.append( r"sed -i 's/DB_DATABASE=laravel/DB_DATABASE=main/g' .env.example" ) if not re.search(r'DB_PASSWORD=password', text): lines.append( r"sed -i 's/DB_PASSWORD=/DB_PASSWORD=password/g' .env.example") for cmdLine in lines: subprocess.call(cmdLine, shell=True, stdout=out, stderr=out, cwd=os.path.join(myCwd, appName)) shutil.copy(envExample, os.path.join(myCwd, appName, '.env'))
def clear_lines(n: int) -> None: """ Erase n previous lines from stdout. :param int n: number of lines of output to clear :return: None """ output = pyout.create_output(sys.stdout) output.cursor_up(n) output.erase_down() output.flush()
def __init__(self, debug: bool = True) -> None: self.debug_ = debug self.prompt = "> " self.bindings = KeyBindings() self.stdout = StdoutProxy(sleep_between_writes=0.5) self.out = create_output(self.stdout) self.alt_out = io.IOBase() self.alt_out.write = self.out.write_raw self.alt_out.flush = self.out.flush self.log_handler = logging.StreamHandler(self.alt_out) log_format = "[{asctime} {levelname}:'{name}']: {message}" time_format = "%Y-%m-%d %H:%M:%S" self.log_formatter = pymine.api.console_log_formatter.CustomFormatter( fmt=log_format, datefmt=time_format, ) self.log_handler.setFormatter(self.log_formatter) self.logger = logging.getLogger() self.logger.addHandler(self.log_handler) if self.debug_: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) self.debug("Started Logger") self.ses = PromptSession( history=FileHistory("./.pmhist"), auto_suggest=AutoSuggestFromHistory(), key_bindings=self.bindings, mouse_support=True, output=self.out, )
import itertools import sys import time from prompt_toolkit.input import create_input from prompt_toolkit.output import create_output from prompt_toolkit.keys import Keys output = create_output(sys.stdout) input_ = create_input(sys.stdin) options = { 1: '1) A', 2: '2) B', 3: '3) C', } chosen = 1 def on_key(key): global chosen if key.key is Keys.Up: chosen -= 1 chosen = max(1, min(len(options), chosen)) elif key.key is Keys.Down: chosen += 1 chosen = max(1, min(len(options), chosen)) def format_text():