Python Subprocess.run() 完成后会自动关闭吗?

0 人关注

如果这是个愚蠢的问题,我表示歉意,然而,我对Python还不是很精通。

关于Python的Subprocess函数...

我看到,当你使用 sp = subprocess.Popen(...) 时,人们会在它运行完命令后关闭/终止它。例子。

sp = subprocess.Popen(['powershell.exe', '-ExecutionPolicy', 'Unrestricted', 'cp', '-r', 'ui', f'..\\{name}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd='UI Boiler')
        sp.wait()
        sp.terminate()

然而,我的问题是,你需要关闭任何subprocess.run()函数吗?还是说这些进程一旦运行完它们的命令就会自动关闭?

我正在进行的项目需要运行大量的这些东西,我不希望因为我没有关闭它们而有10多个shell/powershell/processes打开。

python
subprocess
Adzeiros
Adzeiros
发布于 2022-09-10
1 个回答
lemonhead
lemonhead
发布于 2022-09-10
已采纳
0 人赞同

**是的,在windows和posix实现上都是如此。 subprocess.run() 以及 subprocess.call() 都将被阻止,直到完成,例如通过 Process.wait() 内部。 由于这是一个阻塞式调用,它将等到进程完成后再返回,所以你不需要做任何特别的事情来关闭进程。

以下是相关片段,来自 subprocess source 在cpython-3.10中(为简洁起见而修改)。

def call(*popenargs, timeout=None, **kwargs):
    """..."""
    with Popen(*popenargs, **kwargs) as p:
            return p.wait(timeout=timeout)
        except:  # Including KeyboardInterrupt, wait handled that.
            p.kill()
            raise
# ...
def run(*popenargs,
        input=None, capture_output=False, timeout=None, check=False, **kwargs):
    """..."""
    # ...
    with Popen(*popenargs, **kwargs) as process:
        # communicate (as well as the with statement will both wait() internally
            stdout, stderr = process.communicate(input, timeout=timeout)
        except TimeoutExpired as exc:
            process.kill()
            # ... additional handling here
            raise
        except:  # Including KeyboardInterrupt, communicate handled that.
            process.kill()
            # We don't call process.wait() as .__exit__ does that for us.
            raise
        retcode = process.poll()
        if check and retcode:
            raise CalledProcessError(retcode, process.args,
                                     output=stdout, stderr=stderr)
    return CompletedProcess(process.args, retcode, stdout, stderr)