4

To execute Linux commands in Python we have great modules: os and subprocess. I have integrated Linux commands in the console based python program using both os and subprocess module however the same thing doesn't happen in Django. Take an example of this view:

def hello(request):
    res = os.system('ls')
    return render_to_response('thanks.html', {'res':res}, context_instance=RequestContext(request))

The only thing this view returns is 0. I have tried with subprocess too. The output I get is 0. What's wrong?

Joyfulgrind
  • 2,762
  • 8
  • 34
  • 41

2 Answers2

4

This is not a Django issue. That's what os.system does - it gives the return value of the system call, in this case 0 for a successful execution.

If you need to grab the output of an external program, you should use subprocess.check_output (2.7 only). However, if all you're interested in is a directory listing, there's a better way to do that, which is to use os.listdir.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thank you! os.listdir listed all the directories. However I want to know how to make os.system('ls') to list all the directories. I just used ls to get command working. Instead of ls I want to use: rsync --list-only /home – Joyfulgrind Nov 09 '12 at 10:00
  • As I said, you should use `subprocess.check_output` to grab the output of an external call. You can't do it with `os.system`. – Daniel Roseman Nov 09 '12 at 10:15
  • I am using Django with Debian which has default Python 2.6.6. So, I can't use check_output. Is there any other way? – Joyfulgrind Nov 09 '12 at 10:18
  • See [this answer](http://stackoverflow.com/questions/4814970/subprocess-check-output-doesnt-seem-to-exist-python-2-6-5) for a way to do it in 2.6. – Daniel Roseman Nov 09 '12 at 10:22
0

0 is this case is the return code of the exit status which means "nothing is wrong" in this case.

According to os.system doc:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

Community
  • 1
  • 1
K Z
  • 29,661
  • 8
  • 73
  • 78