2

I'm told subprocess.Popen does not block, so the process runs in the background and your python program does not wait until it has finished. However, this is not what I want.

I'm having my program call into an external python program, which I have no control over. It does not return any return codes, just runs, operates on files, and finishes. I want to call this and only continue my python program when that call has completed. How do I do this?

coffee
  • 35
  • 2

3 Answers3

5

Call communicate or wait on the subprocess.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
2

Use the call method from subprocess.

subprocess.call(*popenargs, **kwargs) Run command with arguments. Wait for command to complete, then return the returncode attribute.

see → http://docs.python.org/library/subprocess.html#subprocess.call

Mario César
  • 3,699
  • 2
  • 27
  • 42
1

Best way is to use the communicate method: http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate

Also have a look at the wait method, it states why most of the time you should use communicate instead: http://docs.python.org/library/subprocess.html#subprocess.Popen.wait

tauran
  • 7,986
  • 6
  • 41
  • 48
  • most of the time? Only if I work with pipes. If I just run a command and want to wait for it, I don't need that. – glglgl Aug 11 '11 at 14:52
  • Most of the time because one should not ignore the output of a process and pipes (are in my opinion) the most convenient way to handle it. And that leads to using `communicate`. – tauran Aug 11 '11 at 15:32
  • Yes and no. Normally yes, but if a process outputs (or expects) megabytes of data, it is most of the time better to fetch the data piece by piece instead of putting it all at once, like `communicate()` does... – glglgl Aug 12 '11 at 06:56
  • the "most of the time" is linked to "not ignore the output". If to use `communicate()` or to handle by myself is IMHO to be determined by the amount of data to be expected. – glglgl Aug 12 '11 at 07:53