使用子流程模块从 VS Code 中获取“考虑使用”代码质量建议

kws*_*314 5 python subprocess

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

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

但我不知道在哪里使用“with”

Bar*_*mar 6

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

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

请注意,try/except还将捕获 主体中的异常with。请参阅此答案,了解如何构建代码以捕获异常subprocess.Popen()

  • 也许我错过了一些东西,但在本节的末尾: https://docs.python.org/3/library/subprocess.html#popen-constructor _Popen 对象通过 with 语句支持作为上下文管理器:退出时,标准文件描述符被关闭,进程正在等待._ (2认同)