code: def exec_cmd(
      cmd,
      *,
      extra_env=None,
      synchronous=True,
      **kwargs,
  ):
      """
      A convenience wrapper of `subprocess.Popen` for running a command from a Python
      script.
      If `synchronous` is True, wait until the process terminated and if subprocess
      return code is not 0, raise error containing last 100 lines output.
      If `synchronous` is False, return an `Popen` instance and a deque instance holding
      tail outputs.
      The subprocess stdout / stderr output will be streamly redirected to current
      process stdout.
      """
      illegal_kwargs = set(kwargs.keys()).intersection(
          {"text", "stdout", "stderr"}
      )
      if illegal_kwargs:
          raise ValueError(
              f"`kwargs` cannot contain {list(illegal_kwargs)}"
          )
  
      env = kwargs.pop("env", None)
      if extra_env is not None and env is not None:
          raise ValueError(
              "`extra_env` and `env` cannot be used at the same time"
          )
  
      env = env if extra_env is None else {**os.environ, **extra_env}
  
      process = subprocess.Popen(
          cmd,
          env=env,
          text=True,
          stdout=subprocess.PIPE,
          stderr=subprocess.STDOUT,
          **kwargs,
      )
  
      tail_output_deque = collections.deque(maxlen=100)
  
      def redirect_log_thread_fn():
          for line in process.stdout:
              # collect tail logs by `tail_output_deque`
              tail_output_deque.append(line)
  
              # redirect to stdout.
              sys.stdout.write(line)
  
      threading.Thread(target=redirect_log_thread_fn, args=()).start()
  
      if not synchronous:
          return process, tail_output_deque
  
      return_code = process.wait()
      if return_code != 0:
          raise RuntimeError(
              gen_cmd_exec_failure_msg(
                  cmd, return_code, tail_output_deque
              )
          )
  
imports: import subprocess
  import os
  import sys
  import random
  import threading
  import collections
  import logging
  import time
label_desc: Use image node_id 3 for calling a global function with example usage: exec_cmd(cmd) and returns: process,  tail_output_deque