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


Python subprocess.CREATE_NEW_PROCESS_GROUP属性代码示例

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


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

示例1: __init__

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def __init__(self, *args: str, environment_variables: typing.Optional[typing.Dict[str, str]] = None):
        cmd = _make_process_args(*args)
        _logger.info('Starting background child process: %s', ' '.join(cmd))

        try:  # Windows-specific.
            # If the current process group is used, CTRL_C_EVENT will kill the parent and everyone in the group!
            creationflags: int = subprocess.CREATE_NEW_PROCESS_GROUP  # type: ignore
        except AttributeError:  # Not on Windows.
            creationflags = 0

        # Buffering must be DISABLED, otherwise we can't read data on Windows after the process is interrupted.
        # For some reason stdout is not flushed at exit there.
        self._inferior = subprocess.Popen(cmd,
                                          stdout=subprocess.PIPE,
                                          stderr=sys.stderr,
                                          encoding='utf8',
                                          env=_get_env(environment_variables),
                                          creationflags=creationflags,
                                          bufsize=0) 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:21,代码来源:_subprocess.py

示例2: setUp

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def setUp(self):
        super(Base, self).setUp()

        self.lines = []
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", 0))
        self.t = threading.Thread(target=self.readlog)
        self.t.daemon = True
        self.t.start()

        examplepy = os.path.join(os.path.dirname(__file__),
                                 "examples.py")
        if os.name == 'posix':
            kwargs = {
                'preexec_fn': os.setsid
            }
        else:
            kwargs = {
                'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP
            }

        self.subp = subprocess.Popen(['python', examplepy, self.name,
                                      str(self.sock.getsockname()[1])],
                                     **kwargs) 
开发者ID:sileht,项目名称:cotyledon,代码行数:27,代码来源:test_functional.py

示例3: terminate

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def terminate(self):
    """Tries to do something saner on Windows that the stdlib.

    Windows:
      self.detached/CREATE_NEW_PROCESS_GROUP determines what can be used:
      - If set, only SIGBREAK can be sent and it is sent to a single process.
      - If not set, in theory only SIGINT can be used and *all processes* in
         the processgroup receive it. In practice, we just kill the process.
      See http://msdn.microsoft.com/library/windows/desktop/ms683155.aspx
      The default on Windows is to call TerminateProcess() always, which is not
      useful.

    On Posix, always send SIGTERM.
    """
    try:
      if sys.platform == 'win32' and self.detached:
        return self.send_signal(signal.CTRL_BREAK_EVENT)
      super(Popen, self).terminate()
    except OSError:
      # The function will throw if the process terminated in-between. Swallow
      # this.
      pass 
开发者ID:luci,项目名称:luci-py,代码行数:24,代码来源:subprocess42.py

示例4: pr_none

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def pr_none():
    import subprocess

    # Start a long running process so we have time to run tests on it before it finishes
    # Put the new process into a separate group so its signal are isolated from ours
    kwargs = dict()
    if sys.platform.startswith('win'):
        command = 'timeout -t 5 /nobreak'
        kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
    else:
        command = 'sleep 5'
        kwargs['start_new_session'] = True

    proc = subprocess.Popen(command, shell=True, **kwargs)
    pr = cu.ProcReader(proc, None, None)
    return pr 
开发者ID:python-cmd2,项目名称:cmd2,代码行数:18,代码来源:test_utils.py

示例5: _run_mlflow_run_cmd

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def _run_mlflow_run_cmd(mlflow_run_arr, env_map):
    """
    Invoke ``mlflow run`` in a subprocess, which in turn runs the entry point in a child process.
    Returns a handle to the subprocess. Popen launched to invoke ``mlflow run``.
    """
    final_env = os.environ.copy()
    final_env.update(env_map)
    # Launch `mlflow run` command as the leader of its own process group so that we can do a
    # best-effort cleanup of all its descendant processes if needed
    if sys.platform == "win32":
        return subprocess.Popen(
            mlflow_run_arr, env=final_env, universal_newlines=True,
            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
    else:
        return subprocess.Popen(
            mlflow_run_arr, env=final_env, universal_newlines=True, preexec_fn=os.setsid) 
开发者ID:mlflow,项目名称:mlflow,代码行数:18,代码来源:__init__.py

示例6: open_process

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def open_process(command, cwd=None, shell=True, _popen_lock=threading.Lock()):
    kwargs = {
        "shell": shell,
        "stdout": subprocess.PIPE,
        "stderr": subprocess.STDOUT,
        "stdin": subprocess.PIPE,
        "bufsize": 1,  # Line buffered
        "universal_newlines": True,
    }

    if cwd is not None:
        kwargs["cwd"] = cwd

    # Prevent signal propagation from parent process
    try:
        # Windows
        kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
    except AttributeError:
        # Unix
        kwargs["preexec_fn"] = os.setpgrp

    with _popen_lock:  # Work around Python 2 Popen race condition
        return subprocess.Popen(command, **kwargs) 
开发者ID:niklasf,项目名称:fishnet,代码行数:25,代码来源:fishnet.py

示例7: _kill_with_event

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def _kill_with_event(self, event, name):
        tagname = "test_os_%s" % uuid.uuid1()
        m = mmap.mmap(-1, 1, tagname)
        m[0] = '0'
        # Run a script which has console control handling enabled.
        proc = subprocess.Popen([sys.executable,
                   os.path.join(os.path.dirname(__file__),
                                "win_console_handler.py"), tagname],
                   creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
        # Let the interpreter startup before we send signals. See #3137.
        count, max = 0, 20
        while count < max and proc.poll() is None:
            if m[0] == '1':
                break
            time.sleep(0.5)
            count += 1
        else:
            self.fail("Subprocess didn't finish initialization")
        os.kill(proc.pid, event)
        # proc.send_signal(event) could also be done here.
        # Allow time for the signal to be passed and the process to exit.
        time.sleep(0.5)
        if not proc.poll():
            # Forcefully kill the process if we weren't able to signal it.
            os.kill(proc.pid, signal.SIGINT)
            self.fail("subprocess did not stop on {}".format(name)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:28,代码来源:test_os.py

示例8: __init__

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
                 logfile=None, cwd=None, env=None, encoding=None,
                 codec_errors='strict', preexec_fn=None):
        super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
                searchwindowsize=searchwindowsize, logfile=logfile,
                encoding=encoding, codec_errors=codec_errors)

        # Note that `SpawnBase` initializes `self.crlf` to `\r\n`
        # because the default behaviour for a PTY is to convert
        # incoming LF to `\r\n` (see the `onlcr` flag and
        # https://stackoverflow.com/a/35887657/5397009). Here we set
        # it to `os.linesep` because that is what the spawned
        # application outputs by default and `popen` doesn't translate
        # anything.
        if encoding is None:
            self.crlf = os.linesep.encode ("ascii")
        else:
            self.crlf = self.string_type (os.linesep)

        kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
                      stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                      cwd=cwd, preexec_fn=preexec_fn, env=env)

        if sys.platform == 'win32':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            kwargs['startupinfo'] = startupinfo
            kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP

        if isinstance(cmd, string_types) and sys.platform != 'win32':
            cmd = shlex.split(cmd, posix=os.name == 'posix')

        self.proc = subprocess.Popen(cmd, **kwargs)
        self.pid = self.proc.pid
        self.closed = False
        self._buf = self.string_type()

        self._read_queue = Queue()
        self._read_thread = threading.Thread(target=self._read_incoming)
        self._read_thread.setDaemon(True)
        self._read_thread.start() 
开发者ID:pypa,项目名称:pipenv,代码行数:43,代码来源:popen_spawn.py

示例9: create_process

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def create_process(self, script_name, env, devnull):
        """
        Creates a subprocess to run the script
        Input:
          script_name: str: Name of the temporary file of the script to run
          env: dict: Holds the environment
          devnull: file object that will be used as stdin
        Return:
          subprocess.Popen that was created
        """
        if self.is_windows():
            exec_cmd = os.path.join(os.path.dirname(__file__), "scripts", "mingw64_runcmd.bat")
            return subprocess.Popen(
                [exec_cmd, script_name],
                env=env,
                shell=False,
                stdin=devnull,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
                )
        else:
            return subprocess.Popen(
                ['/bin/bash', script_name],
                shell=False,
                cwd="/",
                env=env,
                stdin=devnull,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                preexec_fn=os.setsid,
                ) 
开发者ID:idaholab,项目名称:civet,代码行数:34,代码来源:JobRunner.py

示例10: _kill_with_event

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def _kill_with_event(self, event, name):
        tagname = "test_os_%s" % uuid.uuid1()
        m = mmap.mmap(-1, 1, tagname)
        m[0] = 0
        # Run a script which has console control handling enabled.
        proc = subprocess.Popen([sys.executable,
                   os.path.join(os.path.dirname(__file__),
                                "win_console_handler.py"), tagname],
                   creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
        # Let the interpreter startup before we send signals. See #3137.
        count, max = 0, 100
        while count < max and proc.poll() is None:
            if m[0] == 1:
                break
            time.sleep(0.1)
            count += 1
        else:
            # Forcefully kill the process if we weren't able to signal it.
            os.kill(proc.pid, signal.SIGINT)
            self.fail("Subprocess didn't finish initialization")
        os.kill(proc.pid, event)
        # proc.send_signal(event) could also be done here.
        # Allow time for the signal to be passed and the process to exit.
        time.sleep(0.5)
        if not proc.poll():
            # Forcefully kill the process if we weren't able to signal it.
            os.kill(proc.pid, signal.SIGINT)
            self.fail("subprocess did not stop on {}".format(name)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:30,代码来源:test_os.py

示例11: spawn_local

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def spawn_local(self, idx):
        """
        This method launches processes that are needed to run on this computer
        :param idx: An index into launch_db
        """

        # get the launch entry in launch_db
        db_entry = self.launch_db[idx]

        # skip over the entry for the backplane
        # launch the process either in its own window or just launch it.
        # differentiate between windows and other os's.
        if not db_entry['command_string'] == 'backplane':
            if sys.platform.startswith('win32'):
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(db_entry['command_string'],
                                      creationflags=subprocess.CREATE_NEW_CONSOLE)
                else:
                    command_list = db_entry['command_string']
                    self.proc = Popen(command_list, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
            else:
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(['xterm', '-e', db_entry['command_string']],
                                      stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                                      stdout=subprocess.PIPE)
                else:
                    command_list = db_entry['command_string'].split(' ')
                    self.proc = Popen(command_list)

            # update the entry with the launch information
            db_entry['process'] = self.proc
            db_entry['process_id'] = self.proc.pid
            print('{:35} PID = {}'.format(db_entry['command_string'], str(self.proc.pid)))

            # allow a little time for the process to startup
            try:
                time.sleep(0.5)
            except (KeyboardInterrupt, SystemExit):
                self.clean_up() 
开发者ID:MrYsLab,项目名称:python_banyan,代码行数:41,代码来源:bls.py

示例12: __init__

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
                 logfile=None, cwd=None,  env=None, encoding=None,
                 codec_errors='strict'):
        super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
                searchwindowsize=searchwindowsize, logfile=logfile,
                encoding=encoding, codec_errors=codec_errors)

        kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
                      stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                      cwd=cwd, env=env)

        if sys.platform == 'win32':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            kwargs['startupinfo'] = startupinfo
            kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP

        if isinstance(cmd, string_types) and sys.platform != 'win32':
            cmd = shlex.split(cmd, posix=os.name == 'posix')

        self.proc = subprocess.Popen(cmd, **kwargs)
        self.pid = self.proc.pid
        self.closed = False
        self._buf = self.string_type()

        self._read_queue = Queue()
        self._read_thread = threading.Thread(target=self._read_incoming)
        self._read_thread.setDaemon(True)
        self._read_thread.start() 
开发者ID:Zheaoli,项目名称:pipenv-sublime,代码行数:31,代码来源:popen_spawn.py

示例13: open_ipc_subprocess

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def open_ipc_subprocess(parts, **kwargs):
    ''' Sets new process group flags on Windows to support graceful termination. '''
    check.list_param(parts, 'parts', str)

    creationflags = 0
    if sys.platform == 'win32':
        creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
    return subprocess.Popen(parts, creationflags=creationflags, **kwargs) 
开发者ID:dagster-io,项目名称:dagster,代码行数:10,代码来源:ipc.py

示例14: _create_process

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def _create_process(cmd):
    if sys.platform == 'win32':
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
    else:
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE)

    while process.poll() is None:
        output = process.stdout.readline()
        if output:
            print(output.decode('utf-8').strip())
    return process.returncode 
开发者ID:microsoft,项目名称:nni,代码行数:13,代码来源:nni_client.py

示例15: __init__

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import CREATE_NEW_PROCESS_GROUP [as 别名]
def __init__(self, *args, **kwargs):
            # CREATE_NEW_PROCESS_GROUP is used to send Ctrl+C on Windows:
            # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
            new_pgroup = subprocess.CREATE_NEW_PROCESS_GROUP
            flags_to_add = 0
            if ray.utils.detect_fate_sharing_support():
                # If we don't have kernel-mode fate-sharing, then don't do this
                # because our children need to be in out process group for
                # the process reaper to properly terminate them.
                flags_to_add = new_pgroup
            flags_key = "creationflags"
            if flags_to_add:
                kwargs[flags_key] = (kwargs.get(flags_key) or 0) | flags_to_add
            self._use_signals = (kwargs[flags_key] & new_pgroup)
            super(ConsolePopen, self).__init__(*args, **kwargs) 
开发者ID:ray-project,项目名称:ray,代码行数:17,代码来源:services.py


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