0

It is recommended that os.system is used for executing commands from python scripts. Furthermore, it is claimed that redirection operator work in there. For instance here and here. I do

os.system("ls > out.txt")

This works indeed on one of my computers. Another produces

ls: cannot access >: No such file or directory
ls: cannot access out.txt: No such file or directory

I am a bit limited on the other with access right to investigate which process produces this message. But os.system("ls") lists the files like charm. Both are Windows 7 machines.

Community
  • 1
  • 1
Val
  • 1
  • 8
  • 40
  • 64
  • 9
    *It is recommended that os.system*. No, actually, it is not. You should use the `subprocess` module instead. – Martijn Pieters Nov 11 '13 at 12:21
  • 2
    `>` redirection is dependent on the shell being executed; `os.system()` passes the string to a shell process and if that process doesn't support `>` then you get an error. – Martijn Pieters Nov 11 '13 at 12:22
  • @MartijnPieters Why `os.system` is not recommended? – thefourtheye Nov 11 '13 at 12:29
  • @thefourtheye This means that Martijn Pieters does not recommend this. – Val Nov 11 '13 at 12:30
  • I wonder how which are those different shells on Windows 7 installations and which of them fails to support the > redirection. – Val Nov 11 '13 at 12:32
  • 5
    @thefourtheye: `os.system()` is low-level, and a security hole waiting to happen (as soon as you mix in untrusted data into the shell call shell exploits are just an escape character away). `subprocess` gives you much more flexibility and lets you avoid using a shell altogether. – Martijn Pieters Nov 11 '13 at 12:32
  • 2
    @Val Even then, it is Martijn Pieters who doesnt like it. So, there will be a good reason behind it :) – thefourtheye Nov 11 '13 at 12:32
  • 1
    Quoting from the documentation of [`os.system()`](http://docs.python.org/2/library/os#os.system): "The [`subprocess`](http://docs.python.org/2/library/subprocess.html#module-subprocess) module provides more powerful facilities for spawning new processes and retrieving their results; **using that module is preferable to using this function.** See the [Replacing Older Functions with the subprocess Module](http://docs.python.org/2/library/subprocess.html#subprocess-replacements) section in the `subprocess` documentation for some helpful recipes." – Bakuriu Nov 11 '13 at 12:52
  • @Val I was more curious which version of Windows 7 had `ls` as a command :) – Jon Clements Nov 11 '13 at 12:53
  • @JonClements every version, once cygwin installed – Val Nov 11 '13 at 13:47

1 Answers1

6

Err no... as Martijn commented - it's not recommended - use subprocess, e.g.:

import subprocess

with open('myfile.txt', 'w') as fout:
    subprocess.check_call('ls', stdout=fout)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jon Clements
  • 138,671
  • 33
  • 247
  • 280