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


Python Popen.poll方法代碼示例

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


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

示例1: run_playbook

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
def run_playbook(playbook, inventory, *args, **kwargs):
    env = ansible_env(os.environ.copy())
    cmd = ['ansible-playbook', '-i', inventory, playbook] + list(args)

    if verbosity():
        cmd += ['-' + ('v' * verbosity())]

    show_timestamp = False
    if 'timestamp' in kwargs:
        show_timestamp = kwargs['timestamp']
        del kwargs['timestamp']

    output = print
    if show_timestamp:
        output = timestamp

    logger.info('running %s', ' '.join(cmd))
    logger.debug('env: %r', env)

    process = Popen(cmd, env=env, stdout=PIPE,
                    bufsize=1, **kwargs)
    for line in iter(process.stdout.readline, b''):
        output(line[:-1])
    # empty output buffers
    process.poll()
    return process.returncode
開發者ID:AerisCloud,項目名稱:AerisCloud,代碼行數:28,代碼來源:ansible.py

示例2: DummySim

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
class DummySim(ProcessWorkerThread):

    def handle_eval(self, record):
        self.process = Popen(['./sumfun_ext', array2str(record.params[0])],
                             stdout=PIPE)

        val = np.nan
        # Continuously check for new outputs from the subprocess
        while True:
            output = self.process.stdout.readline()
            if output == '' and self.process.poll() is not None:  # No new output
                break
            if output:  # New intermediate output
                try:
                    val = float(output.strip())  # Try to parse output
                    if val > 350:  # Terminate if too large
                        self.process.terminate()
                        self.finish_success(record, 350)
                        return
                except ValueError:  # If the output is nonsense we terminate
                    logging.warning("Incorrect output")
                    self.process.terminate()
                    self.finish_failure(record)
                    return

        rc = self.process.poll()  # Check the return code
        if rc < 0 or np.isnan(val):
            logging.warning("Incorrect output or crashed evaluation")
            self.finish_failure(record)
        else:
            self.finish_success(record, val)
開發者ID:NoobSajbot,項目名稱:pySOT,代碼行數:33,代碼來源:test_subprocess_partial_info.py

示例3: run

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
def run(pro, *args, **kwargs):
    """
    Run vagrant within a project
    :param pro: .project.Project
    :param args: list[string]
    :param kwargs: dict[string,string]
    :return:
    """
    with cd(pro.folder()):
        # fix invalid exports for vagrant
        NFS().fix_anomalies()

        new_env = ansible_env(os.environ.copy())

        new_env['PATH'] = os.pathsep.join([
            new_env['PATH'],
            os.path.join(aeriscloud_path, 'venv/bin')
        ])
        new_env['VAGRANT_DOTFILE_PATH'] = pro.vagrant_dir()
        new_env['VAGRANT_CWD'] = pro.vagrant_working_dir()
        new_env['VAGRANT_DISKS_PATH'] = os.path.join(data_dir(), 'disks')

        # We might want to remove that or bump the verbosity level even more
        if verbosity() >= 4:
            new_env['VAGRANT_LOG'] = 'info'

        new_env['AERISCLOUD_PATH'] = aeriscloud_path
        new_env['AERISCLOUD_ORGANIZATIONS_DIR'] = os.path.join(data_dir(),
                                                               'organizations')

        org = default_organization()
        if org:
            new_env['AERISCLOUD_DEFAULT_ORGANIZATION'] = org

        organization_name = pro.organization()
        if organization_name:
            organization = Organization(organization_name)
        else:
            organization = Organization(org)

        basebox_url = organization.basebox_url()
        if basebox_url:
            new_env['VAGRANT_SERVER_URL'] = basebox_url

        args = ['vagrant'] + list(args)
        logger.debug('running: %s\nenv: %r', ' '.join(args), new_env)

        # support for the vagrant prompt
        if args[1] == 'destroy':
            return call(args, env=new_env, **kwargs)
        else:
            process = Popen(args, env=new_env, stdout=PIPE,
                            bufsize=1, **kwargs)
            for line in iter(process.stdout.readline, b''):
                timestamp(line[:-1])
            # empty output buffers
            process.poll()
            return process.returncode
開發者ID:AerisCloud,項目名稱:AerisCloud,代碼行數:60,代碼來源:vagrant.py

示例4: run_compiler

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
 def run_compiler(self, language, filename, executable_name):
     args = ["g++" if language else "gcc", "-static", "-w", "-O2", filename, "-o",
             executable_name]
     self.log += ['Running: ' + ' '.join(args)]
     proc = Popen(args,
                  cwd=self.base_dir, stdin=PIPE, stdout=PIPE, stderr=PIPE)
     output = proc.communicate(timeout=self.COMPILE_TIMEOUT)
     self.log += [str(output[1])]
     if proc.poll() is None:
         try:
             self.log += ['Compile timeout.']
             proc.kill()
         except Exception:
             pass
     self.log += ["Compiler returns %d." % proc.returncode]
     if proc.returncode:
         raise CompileErrorException()
開發者ID:ruc-acm,項目名稱:online-vs-platform,代碼行數:19,代碼來源:judge-daemon.py

示例5: check_output

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
def check_output(*popenargs, **kwargs):
    """
    Re-implement check_output from subprocess32, but with a timeout that kills
    child processes.

    See https://github.com/google/python-subprocess32/blob/master/subprocess32.py#L606
    """
    timeout = kwargs.pop('timeout', None)
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, preexec_fn=os.setsid, *popenargs, **kwargs)
    try:
        output = process.communicate(timeout=timeout)[0]
    except TimeoutExpired as error:
        os.killpg(process.pid, signal.SIGINT)
        raise error
    retcode = process.poll()
    if retcode:
        raise CalledProcessError(retcode, process.args, output=output)
    return output
開發者ID:innisfree,項目名稱:pymath,代碼行數:22,代碼來源:timeout.py

示例6: check_output

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.
    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.
    The arguments are the same as for the Popen constructor.  Example:
    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.
    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    'ls: non_existent_file: No such file or directory\n'
    """

    timeout = kwargs.pop('timeout', None)
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    if _kill_processes.is_set():
        raise TerminateSignaled()

    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    _processes.append(process)

    try:
        output, unused_err = process.communicate(timeout=timeout)
        _processes.remove(process)

    except TimeoutExpired:
        _processes.remove(process)
        process.kill()
        output, unused_err = process.communicate()
        raise TimeoutExpired(process.args, timeout, output=output)

    retcode = process.poll()
    if retcode:
        raise CalledProcessError(retcode, process.args, output=output)
    return output
開發者ID:metocean,項目名稱:gregc,代碼行數:42,代碼來源:subprocess_thread_tool.py

示例7: run2

# 需要導入模塊: from subprocess32 import Popen [as 別名]
# 或者: from subprocess32.Popen import poll [as 別名]
def run2(command, check=True, timeout=None, *args, **kwargs):
    ''' Run a command.

        If check=True (the default),
        then if return code is not zero or there is stderr output,
        raise CalledProcessError. Return any output in the exception.

        If timeout (in seconds) is set and command times out, raise TimeoutError. '''

    ''' Parts from subprocess32.check_output(). '''

    raise Exception('Deprecated. Use the sh module.')

    # use subprocess32 for timeout
    from subprocess32 import Popen, CalledProcessError, TimeoutExpired

    process = Popen(command, stdout=stdout, stderr=stderr, *args, **kwargs)
    try:
        process.wait(timeout=timeout)
    except TimeoutExpired:
        print('TimeoutExpired') #DEBUG
        #print('stdout: %s, (%d)' % (str(stdout), len(str(stdout)))) #DEBUG
        #print('stderr: %s, (%d)' % (str(stderr), len(str(stderr)))) #DEBUG
        try:
            process.kill()
            process.wait()
        finally:
            print('after kill/wait') #DEBUG
            #print('stdout: %s, (%d)' % (str(stdout), len(str(stdout)))) #DEBUG
            #print('stderr: %s, (%d)' % (str(stderr), len(str(stderr)))) #DEBUG
            raise TimeoutExpired(process.args, timeout)

    if check:
        retcode = process.poll()
        if retcode:
            raise CalledProcessError(retcode, process.args)
開發者ID:goodcrypto,項目名稱:goodcrypto-libs,代碼行數:38,代碼來源:utils.py


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