当前位置: 首页>>代码示例>>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;未经允许,请勿转载。