5

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'

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
kwsong0314
  • 221
  • 4
  • 11

1 Answers1

6

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().

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Won't this make the subprocess blocking? – etauger Nov 11 '22 at 20:28
  • If `subprocess.Popen()` blocks, it will block in either version. – Barmar Nov 11 '22 at 20:29
  • 1
    But it doesn't block, and using `with` won't make it blocking. – Barmar Nov 11 '22 at 20:30
  • I don't see anything in the documentation that says that the context manager blocks. – Barmar Nov 11 '22 at 20:38
  • 2
    Maybe I'm missing something, but at the end of this section: https://docs.python.org/3/library/subprocess.html#popen-constructor _Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for._ – etauger Nov 11 '22 at 20:40
  • That's on *exit*, not when it starts. – Barmar Nov 11 '22 at 20:41
  • I see your appoint. The advice assumes that you're going to process all the output of the subprocess, so you'll eventually wait for the process to exit. All that code should be inside the `with`. – Barmar Nov 11 '22 at 20:45
  • So my real question I guess is: if we want to launch an independent process (one for which we don't want to wait that it exits), we cannot use a context manager? Therefore, our only hope to satisfy pylint is to disable the warning? – etauger Nov 11 '22 at 21:09
  • Of course. In general you only use a context manager when you're using the resource within a local context. – Barmar Nov 11 '22 at 21:25
  • You shouldn't disable the warning globally, use a comment to suppress it for that call. – Barmar Nov 11 '22 at 21:25
  • 1
    This doesn't work, I wanted to remove an error `consider-using-with` but now my process is blocking. – Dimitri Kopriwa Mar 08 '23 at 13:47
  • It's not an error, it's just a style warning. And it's not appropriate if you need to use the resource more dynamically than a context manager allows. So you should suppress it when it doesn't fit your use. – Barmar Mar 08 '23 at 15:37