'consider-using-with' 来自 VS Code 使用子进程模块的代码质量建议

'consider-using-with' code quality suggestion from VS Code using subprocess module

我使用了subprocess.popen如下。以下 linter 建议出现在 vscode

try:
            p = subprocess.Popen(
                ["python", "app.py"]
            )
except:
            traceback.print_exc()
Consider using 'with' for resource-allocating operationspylint(consider-using-with)

但是不知道用在什么地方'with'

使用with分配来自subprocess.popen()的变量。

try:
    with subprocess.Popen(['python', 'app.py']) as p:
        # code here
except:
    traceback.print_exc()

请注意 try/except 也会在 with 的主体中捕获异常。请参阅 this answer 以了解如何构造代码以捕获来自 subprocess.Popen() 的异常。