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

Viewed 2237

I used subprocess.popen as follows. The following linter suggestion occurs in vscode

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

But I don't know where to use 'with'

1 Answers

Use with to assign the variable from subprocess.popen().

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

Note that the try/except will also catch exceptions in the body of with. See this answer for how you can structure the code to just catch an exception from subprocess.Popen().

Related