當前位置: 首頁>>代碼示例>>Python>>正文


Python subprocess.TimeoutExpired方法代碼示例

本文整理匯總了Python中subprocess.TimeoutExpired方法的典型用法代碼示例。如果您正苦於以下問題:Python subprocess.TimeoutExpired方法的具體用法?Python subprocess.TimeoutExpired怎麽用?Python subprocess.TimeoutExpired使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在subprocess的用法示例。


在下文中一共展示了subprocess.TimeoutExpired方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def main(_):
  shard_urls = fetch.get_urls_for_shard(FLAGS.urls_dir, FLAGS.shard_id)
  num_groups = int(math.ceil(len(shard_urls) / fetch.URLS_PER_CLIENT))
  tf.logging.info("Launching get_references_web_single_group sequentially for "
                  "%d groups in shard %d. Total URLs: %d",
                  num_groups, FLAGS.shard_id, len(shard_urls))
  command_prefix = FLAGS.command.split() + [
      "--urls_dir=%s" % FLAGS.urls_dir,
      "--shard_id=%d" % FLAGS.shard_id,
      "--debug_num_urls=%d" % FLAGS.debug_num_urls,
  ]
  with utils.timing("all_groups_fetch"):
    for i in range(num_groups):
      command = list(command_prefix)
      out_dir = os.path.join(FLAGS.out_dir, "process_%d" % i)
      command.append("--out_dir=%s" % out_dir)
      command.append("--group_id=%d" % i)
      try:
        # Even on 1 CPU, each group should finish within an hour.
        sp.check_call(command, timeout=60*60)
      except sp.TimeoutExpired:
        tf.logging.error("Group %d timed out", i) 
開發者ID:akzaidi,項目名稱:fine-lm,代碼行數:24,代碼來源:get_references_web.py

示例2: test_reloader_live

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def test_reloader_live(runargs, mode):
    with TemporaryDirectory() as tmpdir:
        filename = os.path.join(tmpdir, "reloader.py")
        text = write_app(filename, **runargs)
        proc = Popen(argv[mode], cwd=tmpdir, stdout=PIPE, creationflags=flags)
        try:
            timeout = Timer(5, terminate, [proc])
            timeout.start()
            # Python apparently keeps using the old source sometimes if
            # we don't sleep before rewrite (pycache timestamp problem?)
            sleep(1)
            line = scanner(proc)
            assert text in next(line)
            # Edit source code and try again
            text = write_app(filename, **runargs)
            assert text in next(line)
        finally:
            timeout.cancel()
            terminate(proc)
            with suppress(TimeoutExpired):
                proc.wait(timeout=3) 
開發者ID:huge-success,項目名稱:sanic,代碼行數:23,代碼來源:test_reloader.py

示例3: _exec_global

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def _exec_global(self, search_args, context, input=None):
        command = ['global', '-q'] + search_args
        global_proc = subprocess.Popen(
            command,
            cwd=context['path'],
            universal_newlines=True,
            stdin=subprocess.PIPE if input else None,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        try:
            output, error = global_proc.communicate(input=input, timeout=15)
        except subprocess.TimeoutExpired:
            global_proc.kill()
            output, error = global_proc.communicate()
        global_exitcode = global_proc.returncode

        if global_exitcode != 0:
            self._print_global_error(global_exitcode, error)
            return []

        return [t for t in output.split('\n') if len(t) > 0] 
開發者ID:ozelentok,項目名稱:denite-gtags,代碼行數:23,代碼來源:gtags_base.py

示例4: execute

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def execute(d):
  with open("sample.bin", "wb") as f:
    f.write(d)
  
  try:
    cp = subprocess.run(
      [
          "gdb.exe", "--batch",  "--return-child-result", "-x", "fuzz.gdb",
          BINARY_PATH
      ],
      stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True,
      timeout=2.0)
  except subprocess.TimeoutExpired as e:
    sys.stdout.write("T")
    return (False, "")

  report = ""
  magic = "------------------------------"
  crashed = cp.returncode >= 0xc0000000
  if crashed:
    #print(cp.stdout)
    report = cp.stdout.split(magic)[1]

  return (crashed, report) 
開發者ID:gynvael,項目名稱:stream,代碼行數:26,代碼來源:fuzz.py

示例5: start_or_restart_ffmpeg

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def start_or_restart_ffmpeg(ffmpeg_cmd, frame_size, ffmpeg_process=None):
    if not ffmpeg_process is None:
        print("Terminating the existing ffmpeg process...")
        ffmpeg_process.terminate()
        try:
            print("Waiting for ffmpeg to exit gracefully...")
            ffmpeg_process.communicate(timeout=30)
        except sp.TimeoutExpired:
            print("FFmpeg didnt exit. Force killing...")
            ffmpeg_process.kill()
            ffmpeg_process.communicate()
        ffmpeg_process = None

    print("Creating ffmpeg process...")
    print(" ".join(ffmpeg_cmd))
    process = sp.Popen(ffmpeg_cmd, stdout = sp.PIPE, stdin = sp.DEVNULL, bufsize=frame_size*10, start_new_session=True)
    return process 
開發者ID:blakeblackshear,項目名稱:frigate,代碼行數:19,代碼來源:video.py

示例6: do_subprocess

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def do_subprocess(cmd, stdout=True, stderr=True, check=True, timeout=2):
    assert sys.version_info >= (3,5)
    kwargs = dict(
        stdout=subprocess.PIPE if stdout else None,
        stderr=subprocess.PIPE if stderr else None,
        shell=True,
        check=False,
        timeout=timeout,
    )

    try:
        result = subprocess.run(cmd, **kwargs)
    except subprocess.TimeoutExpired:
        msg = "Command '{}' timed out after waiting for {} seconds"
        raise ClickException(msg.format(cmd, timeout))

    if check and result.returncode:
        errno = result.returncode
        error = result.stderr.decode().strip()
        msg = "Command '{}' returned non-zero exit status {}\n{}"
        raise ClickException(msg.format(cmd, errno, error))

    return result 
開發者ID:kblomqvist,項目名稱:yasha,代碼行數:25,代碼來源:filters.py

示例7: _wait_for_containers_exit_status

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def _wait_for_containers_exit_status(self, containers):
        """Wait for all of the specified containers to exit
        and return their exit codes.
        Args:
            containers (list of str): The containers to wait to exit.

        Returns:
            list of int: The list of return codes for the process in each
                container.

        """
        wait = ['docker', 'wait'] + containers
        handle = subprocess.Popen(
            args=wait,
            stdout=subprocess.PIPE,
            universal_newlines=True)
        try:
            output, _ = handle.communicate(timeout=35)
            return [int(e) for e in output.strip().split('\n')]
        except subprocess.TimeoutExpired:
            handle.kill()
            LOGGER.warning("Docker timed out waiting for %s to exit",
                           containers)
            return [] 
開發者ID:hyperledger,項目名稱:sawtooth-core,代碼行數:26,代碼來源:test_shutdown_smoke.py

示例8: _run

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def _run(*args, env=None, check=False, timeout=None):
    encoded_args = [a.encode('utf-8') for a in args] if sys.platform != 'win32' else args
    with subprocess.Popen(encoded_args, env=env, stdout=PIPE, stderr=PIPE) as process:
        try:
            stdout, stderr = process.communicate(input, timeout=timeout)
        except TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise TimeoutExpired(
                process.args, timeout, output=stdout, stderr=stderr,
            )
        except Exception:
            process.kill()
            process.wait()
            raise
        retcode = process.poll()
        if check and retcode:
            raise subprocess.CalledProcessError(
                retcode, process.args, output=stdout, stderr=stderr,
            )
        return subprocess.CompletedProcess(process.args, retcode, stdout, stderr) 
開發者ID:smarkets,項目名稱:marge-bot,代碼行數:23,代碼來源:git.py

示例9: runpytest_subprocess

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def runpytest_subprocess(self, *args, timeout=None):
        """Run pytest as a subprocess with given arguments.

        Any plugins added to the :py:attr:`plugins` list will be added using the
        ``-p`` command line option.  Additionally ``--basetemp`` is used to put
        any temporary files and directories in a numbered directory prefixed
        with "runpytest-" to not conflict with the normal numbered pytest
        location for temporary files and directories.

        :param args: the sequence of arguments to pass to the pytest subprocess
        :param timeout: the period in seconds after which to timeout and raise
            :py:class:`Testdir.TimeoutExpired`

        Returns a :py:class:`RunResult`.
        """
        __tracebackhide__ = True
        p = py.path.local.make_numbered_dir(
            prefix="runpytest-", keep=None, rootdir=self.tmpdir
        )
        args = ("--basetemp=%s" % p,) + args
        plugins = [x for x in self.plugins if isinstance(x, str)]
        if plugins:
            args = ("-p", plugins[0]) + args
        args = self._getpytestargs() + args
        return self.run(*args, timeout=timeout) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:27,代碼來源:pytester.py

示例10: tearDown

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def tearDown(self, *args, **kwargs):
        if self.cli_process is not None:
            try:
                self.cli_process.terminate()
                self.cli_process.wait(5)
            except TimeoutExpired:
                try:
                    self.cli_process.kill()
                    self.cli_process.wait(5)
                except Exception as e:
                    logging.critical("cannot stop subprocess {}: {}".format(self.cli_process, e))

            if self.cli_process.returncode != 0:
                self.fail("subprocess {} returned exit code {}".format(' '.join(self.cli_args), self.cli_process.returncode))

        if self.stdout_reader_thread is not None:
            self.stdout_reader_thread.join(5)
            if self.stdout_reader_thread.is_alive():
                logging.error("reader thread not stopping...")

        if self.stderr_reader_thread is not None:
            self.stderr_reader_thread.join(5)
            if self.stderr_reader_thread.is_alive():
                logging.error("reader thread not stopping...") 
開發者ID:IntegralDefense,項目名稱:ACE,代碼行數:26,代碼來源:test_ace.py

示例11: run

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def run(self):
        try:
            script_output = subprocess.check_output(" ".join(self.gdb_cmd), shell=True, stderr=subprocess.DEVNULL,
                                                    stdin=subprocess.DEVNULL)
        except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
            script_output = e.output

        script_output = script_output.decode(errors='replace').splitlines()

        for line in script_output:
            matching = [line.replace(g, '') for g in self.grep_for if g in line]
            matching = " ".join(matching).strip('\' ')
            matching = matching.replace(self.out_dir, '')
            if len(matching) > 0:
                self.out_queue_lock.acquire()
                self.out_queue.put(matching)
                self.out_queue_lock.release() 
開發者ID:rc0r,項目名稱:afl-utils,代碼行數:19,代碼來源:AflThread.py

示例12: check_screen

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def check_screen():
    inside_screen = False
    # try:
    #     screen_output = subprocess.check_output("screen -ls", shell=True, stderr=subprocess.DEVNULL,
    #                                             universal_newlines=True)
    # except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
    #     screen_output = e.output
    #
    # screen_output = screen_output.splitlines()
    #
    # for line in screen_output:
    #     if "(Attached)" in line:
    #         inside_screen = True

    if os.environ.get("STY"):
        inside_screen = True

    return inside_screen 
開發者ID:rc0r,項目名稱:afl-utils,代碼行數:20,代碼來源:afl_multicore.py

示例13: shutdown

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def shutdown(self, grace_time=10) -> bool:
        """
        Tru to stop within <gracetime> seconds the current processus/worker
        :param grace_time: maximum waiting time
        :return: True if stopped, False otherwise
        """
        self.logger.info(f"Trying to stop (terminate) {self.process}")
        try:
            self.process.terminate()
            time.sleep(0.2)
        finally:
            try:
                self.process.wait(timeout=grace_time)
            except subprocess.TimeoutExpired:
                self.logger.info(f"Processus {self.process} did not terminate in time. Trying to kill it.")
            finally:
                try:
                    self.process.kill()
                    self.logger.info(f"Processus exited with {self.process.returncode}")
                    return True
                except subprocess.TimeoutExpired:
                    self.logger.info(f"Processus {self.process} is still alive .. Don't know how to stop it.")
                    return False 
開發者ID:CIRCL,項目名稱:douglas-quaid,代碼行數:25,代碼來源:worker_process.py

示例14: run_command

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def run_command(args, asynchronous=False):
    """Executes a command returning its exit code and output."""
    logging.info("Executing %s command %s.",
                 asynchronous and 'asynchronous' or 'synchronous', args)

    process = subprocess.Popen(args,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)

    try:
        timeout = asynchronous and 1 or None
        output = process.communicate(timeout=timeout)[0].decode('utf8')
    except subprocess.TimeoutExpired:
        pass

    if asynchronous:
        return PopenOutput(None, 'Asynchronous call.')
    else:
        return PopenOutput(process.returncode, output) 
開發者ID:F-Secure,項目名稱:see,代碼行數:22,代碼來源:agent.py

示例15: _run_vsm

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import TimeoutExpired [as 別名]
def _run_vsm(self, cmd, input_data, sig_num_path, wait_time_ms):
        data = (input_data + self.quit_command).encode('utf8')

        timeout_s = 2
        if wait_time_ms > 0:
            timeout_s = wait_time_ms / 1000

        process = Popen(cmd, stdin=PIPE, stdout=PIPE)

        try:
            output, _ = process.communicate(data, timeout_s)
        except TimeoutExpired:
            process.kill()
            return None

        cmd_output = output.decode()

        return _remove_timestamp(cmd_output) 
開發者ID:GENIVI,項目名稱:vehicle_signal_manager,代碼行數:20,代碼來源:tests.py


注:本文中的subprocess.TimeoutExpired方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。