os.system vs subprocess

Tim Golden mail at timgolden.me.uk
Mon Jun 22 03:57:40 EDT 2009


Nate wrote:
> Thanks for your response. Related to this talk about shells, maybe you
> could point me towards a resource where I could read about how windows
> commands are processed w/w/o shells?  I guess I assumed all subprocess
> commands were intepreted by the same thing, cmd.exe., or perhaps the
> shell.

Just a comment here: on Windows, you almost *never* need to specify
shell=True. Certainly, far less than most people seem to think you
need to. The only things which certainly need shell to be set True
are those which don't really exist as programs in their own right:
dir, copy etc. You don't need to set it for batch files (altho' this
does seem to vary slightly between versions) and you certainly don't
need to set it for console programs in general, such as Python.


<code>
import subprocess

subprocess.call (["dir"], shell=False)
subprocess.call (["dir"], shell=True)

with open ("test.bat", "w") as f:
  f.write ("echo hello")

subprocess.call (["test.bat"], shell=False)

subprocess.call (["python", "-c", "import sys; print sys.executable"], shell=False)

</code>

This all works as expected using Python 2.6.1 on WinXP SP3

TJG



More information about the Python-list mailing list