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?

1
  • P.S I have properly called the varilable res as {{ rs }} in template. Commented Nov 9, 2012 at 9:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
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.
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?
See this answer for a way to do it in 2.6.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.