当前位置: 首页>>代码示例>>Python>>正文


Python Popen.kill方法代码示例

本文整理汇总了Python中subprocess32.Popen.kill方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.kill方法的具体用法?Python Popen.kill怎么用?Python Popen.kill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在subprocess32.Popen的用法示例。


在下文中一共展示了Popen.kill方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [as 别名]
def run():
    is_timeout = False
    code = request.form.get('code')
    stdin = request.form.get('stdin')
    code_filename = "/tmp/" + str(uuid4())
    try:
        with open(code_filename, "w") as code_file:
            code_file.write(code)
        p = Popen(
            ['bbm', code_filename],
            stdout=PIPE,
            stdin=PIPE,
            stderr=PIPE
        )
        stdout, stderr = p.communicate(input=stdin.encode('utf-8'), timeout=15)
    except TimeoutExpired:
        is_timeout = True
        p.kill()
        stdout, stderr = p.communicate()
    finally:
        remove(code_filename)
    stdout = stdout.decode('utf-8')
    stderr = stderr.decode('utf-8')
    return jsonify({
        'stdout': stdout,
        'stderr': stderr,
        'is_timeout': is_timeout
    })
开发者ID:bibim-lang,项目名称:pybibim-web-demo,代码行数:30,代码来源:__init__.py

示例2: run_compiler

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [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

示例3: check_output

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [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

示例4: kill

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [as 别名]
    def kill(self, exitCode=-1, gracePeriod=None, sig=None):
        """Kill process.

        "exitCode" this sets what the process return value will be.
        "gracePeriod" [deprecated, not supported]
        "sig" (Unix only) is the signal to use to kill the process. Defaults
            to signal.SIGKILL. See os.kill() for more information.
        """
        if gracePeriod is not None:
            import warnings
            warnings.warn("process.kill() gracePeriod is no longer used",
                          DeprecationWarning)

        # Need to ensure stdin is closed, makes it easier to end the process.
        if self.stdin is not None:
            self.stdin.close()

        if sys.platform.startswith("win"):
            # TODO: 1) It would be nice if we could give the process(es) a
            #       chance to exit gracefully first, rather than having to
            #       resort to a hard kill.
            #       2) May need to send a WM_CLOSE event in the case of a GUI
            #       application, like the older process.py was doing.
            Popen.kill(self)
        else:
            if sig is None:
                sig = signal.SIGKILL
            try:
                if self.__use_killpg:
                    os.killpg(self.pid, sig)
                else:
                    os.kill(self.pid, sig)
            except OSError, ex:
                if ex.errno != 3:
                    # Ignore:   OSError: [Errno 3] No such process
                    raise
            self.returncode = exitCode
开发者ID:13767870821,项目名称:SublimeCodeIntel,代码行数:39,代码来源:process.py

示例5: __init__

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [as 别名]
class UserProgram:
    def __init__(self, path):
        self.path = path
        self.process = None
        self.timeout = 1.0
        self.timer = None
        self.tle = False

    def execute(self):
        if not self.path:
            raise ValueError("Path cannot be empty.")
        self.process = Popen(self.path, stdin=PIPE, stdout=PIPE, stderr=PIPE)

    def start_timer(self):
        self.timer = Timer(self.timeout, self.time_limit_exceeded)
        self.timer.start()

    def stop_timer(self):
        self.timer.cancel()
        self.timer = None

    def read_line(self):
        return self.process.stdout.readline()

    def write_line(self, line):
        self.process.stdout.write(line)

    def kill_process(self):
        try:
            self.process.kill()
        except Exception:
            pass

    def time_limit_exceeded(self):
        self.tle = True
        self.kill_process()
开发者ID:ruc-acm,项目名称:online-vs-platform,代码行数:38,代码来源:judge-client.py

示例6: run2

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [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

示例7: update

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [as 别名]
    def update(self, jobs):
        """
        Update job states to match their current state in PBS queue.

        :param jobs: A list of Job instances for jobs to be updated.
        """
        # Extract list of user names associated to the jobs
        _users = []
        for _service in G.SERVICE_STORE.values():
            if _service.config['username'] not in _users:
                _users.append(_service.config['username'])

        # We agregate the jobs by user. This way one qstat call per user is
        # required instead of on call per job
        _job_states = {}
        for _usr in _users:
            try:
                # Run qstat
                logger.log(VERBOSE, "@PBS - Check jobs state for user %s", _usr)
                _opts = ["/usr/bin/qstat", "-f", "-x", "-u", _usr]
                logger.log(VERBOSE, "@PBS - Running command: %s", _opts)
                _proc = Popen(_opts, stdout=PIPE, stderr=STDOUT)
                # Requires subprocess32 module from pip
                _output = _proc.communicate(timeout=conf.pbs_timeout)[0]
                logger.log(VERBOSE, _output)
                # Check return code. If qstat was not killed by signal Popen
                # will not rise an exception
                if _proc.returncode != 0:
                    raise OSError((
                        _proc.returncode,
                        "/usr/bin/qstat returned non zero exit code.\n%s" %
                        str(_output)
                    ))
            except TimeoutExpired:
                _proc.kill()
                logger.error("@PBS - Unable to check jobs state.",
                             exc_info=True)
                return
            except:
                logger.error("@PBS - Unable to check jobs state.",
                             exc_info=True)
                return

            # Parse the XML output of qstat
            try:
                _xroot = ET.fromstring(_output)
                for _xjob in _xroot.iter('Job'):
                    _xjid = _xjob.find('Job_Id').text
                    _xstate = _xjob.find('job_state').text
                    _xexit = _xjob.find('exit_status')
                    if _xexit is not None:
                        _xexit = _xexit.text
                    _job_states[_xjid] = (_xstate, _xexit)
            except:
                logger.error("@PBS - Unable to parse qstat output.",
                             exc_info=True)
                return
            logger.log(VERBOSE, _job_states)

        # Iterate through jobs
        for _job in jobs:
            # TODO rewrite to get an array JID -> queue from SchedulerQueue table with single SELECT
            _pbs_id = str(_job.scheduler.id)
            # Check if the job exists in the PBS
            if _pbs_id not in _job_states:
                _job.die('@PBS - Job %s does not exist in the PBS', _job.id())
            else:
                # Update job progress output
                self.progress(_job)
                _new_state = 'queued'
                _exit_code = 0
                _state = _job_states[_pbs_id]
                logger.log(VERBOSE, "@PBS - Current job state: '%s' (%s)",
                           _state[0], _job.id())
                # Job has finished. Check the exit code.
                if _state[0] == 'C':
                    _new_state = 'done'
                    _msg = 'Job finished succesfully'

                    _exit_code = _state[1]
                    if _exit_code is None:
                        _new_state = 'killed'
                        _msg = 'Job was killed by the scheduler'
                        _exit_code = ExitCodes.SchedulerKill

                    _exit_code = int(_exit_code)
                    if _exit_code > 256:
                        _new_state = 'killed'
                        _msg = 'Job was killed by the scheduler'
                    elif _exit_code > 128:
                        _new_state = 'killed'
                        _msg = 'Job was killed'
                    elif _exit_code > 0:
                        _new_state = 'failed'
                        _msg = 'Job finished with error code'

                    try:
                        _job.finish(_msg, _new_state, _exit_code)
                    except:
                        _job.die('@PBS - Unable to set job state (%s : %s)' %
#.........这里部分代码省略.........
开发者ID:cis-gov-pl,项目名称:app-service-server,代码行数:103,代码来源:Schedulers.py

示例8: change_password

# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import kill [as 别名]
def change_password(username, current_password, new_password):
    msg_to_web = None
    
    # Popen executes smbpasswd as a child program in a new process,
    # with arguments to the program smbpasswd in a list [].
    #
    # The -s option causes smbpasswd to read from stdin instead of prompting the user.
    # The -U [username] option allows a user to change his/her own password.
    #
    # stdin, stdout and stderr are assigned as PIPE so that we can
    # use communicate() to provide input to stdin of smbpasswd and
    # get message of both success and error back from the program.
    #
    # shell=False in order to avoid the security risk with shell 
    # injection from unsanitized input such as "input; rm -rf /".
    smbpasswd_proc = Popen([u"smbpasswd", u"-s", u"-r", SMB_SERVER, u"-U", username],
                                 stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False)

    try:
        # Space, '.' and newline are inconsistently used in the output from smbpasswd
        # and therefore we strip those characters from the end of the output so that
        # we can do sane regex matching without fearing that one day someone will fix
        # this and break our application.
        smbpasswd_output = (smbpasswd_proc.communicate(
                                    input=(current_password + u'\n'
                                           + new_password   + u'\n'
                                           + new_password   + u'\n')
                                           .encode("UTF-8"), timeout=30)[0]
                                           ).rstrip(u' .\n') 
    except TimeoutExpired:
        smbpasswd_proc.kill()
        log_to_file(u"TIME_OUT: User: %s: subprocess.communicate timed out." % username)
        smbpasswd_output_to_logfile(smbpasswd_output)
        return u"The operation timed out. Please contact your system administrator."

    # According to the output from smbpasswd, decide what message should be shown 
    # in the log and on the web page. 
    if smbpasswd_output.endswith(u'NT_STATUS_LOGON_FAILURE'):
        msg_to_web = translate_message(u"change_password", u"1") 
        log_to_file("AUTH_FAIL: User: %s entered invalid USERNAME or PASSWORD." % username)
        smbpasswd_output_to_logfile(smbpasswd_output)

    # Not all configurations of samba provides this information.
    # "map to guest = bad user" is needed in /etc/samba/smb.conf to make this work.         
    elif smbpasswd_output.endswith(u'NT_STATUS_RPC_PROTOCOL_ERROR'):
        msg_to_web = translate_message(u"change_password", u"2")
        log_to_file(u"Error: User: %s: Incorrect USERNAME" % username)
        smbpasswd_output_to_logfile(smbpasswd_output)

    elif smbpasswd_output.endswith(u'NT_STATUS_UNSUCCESSFUL'):
        msg_to_web = translate_message(u"change_password", u"3")
        log_to_file(u"Error: Could not connect to the Samba server. " 
                    u"Server down or unreachable.")
        smbpasswd_output_to_logfile(smbpasswd_output)

    elif smbpasswd_output.endswith(u'NT_STATUS_INVALID_PARAMETER'):
        msg_to_web = translate_message(u"change_password", u"4")
        log_to_file(u"Error: Invalid parameter detected for smbpasswd.")
        smbpasswd_output_to_logfile(smbpasswd_output)

    elif smbpasswd_output.endswith(u'Error was : Password restriction'):
        msg_to_web = translate_message(u"change_password", u"5")
        log_to_file(u"Error: User: %s tried to change her/his password. But it did " 
                    u"not conform to the policy set by Samba" %  username)
        smbpasswd_output_to_logfile(smbpasswd_output)
    
    elif smbpasswd_output.startswith(u'Unable to find an IP address for'):
        msg_to_web = translate_message(u"change_password", u"6")
        log_to_file(u"ServerName_Error: Server name/address in gsmbpasswd.conf is invalid.")
        smbpasswd_output_to_logfile(smbpasswd_output)
     
    elif smbpasswd_output.startswith(u'Password changed for user'):
        msg_to_web = translate_message(u"change_password", u"7")
        log_to_file(u"SUCCESS: User: %s changed password successfully." % username)
        smbpasswd_output_to_logfile(smbpasswd_output)
        
    return msg_to_web
开发者ID:Gsmbpasswd,项目名称:gsmbpasswd,代码行数:79,代码来源:gsmbpasswd-https.py


注:本文中的subprocess32.Popen.kill方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。