0

I was experimenting with getting python to interact with my terminal, and i tried the following script, and it returned 0, when i expected it to show the contents of the current directory:

>>> import os
>>> os.system("ls")
0

Why does it do this? (note this is a mac command, as i'm on a mac)

TheSporech
  • 17
  • 5
  • 3
    This might be of interest: http://stackoverflow.com/questions/3791465/python-os-system-for-command-line-call-linux-not-returning-what-it-should – jpw Oct 29 '15 at 17:32
  • That command does print the contents of the current directory, but only prints – OneCricketeer Oct 29 '15 at 17:33
  • look at the [docs](https://docs.python.org/2/library/os.html#os.system). It says the returned value is 0 when the command completes successfully. – pushkin Oct 29 '15 at 17:33
  • 1
    BTW, I hope that this is just an example -- calling `ls` is the wrong way to get a list of filenames in Python (for many of the same reasons it's the wrong way to programatically get filenames in bash; see http://mywiki.wooledge.org/ParsingLs) – Charles Duffy Oct 29 '15 at 17:35

4 Answers4

5

0 is the exit status of ls when it completes successfully.

If you want to capture a list of filenames, you want its stdout, not its exit status. os.system() doesn't return that.

I'd suggest:

import subprocess
output = subprocess.check_output(["ls"]) # will raise an exception if ls fails
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Ah, that makes sense. How would i make it so it prints the terminal output to the shell? – TheSporech Oct 29 '15 at 17:33
  • Eh? Using `os.system()` should *already* be passing output straight to stdout -- which won't make it accessible to Python as a variable, but *will* print it straight to the terminal your Python shell is using. If you want to capture output to a Python variable, see the update using the subprocess module for that. – Charles Duffy Oct 29 '15 at 17:37
1

Well, that's how the os.system function works (From the python doc):

On Unix, the return value is the exit status of the process encoded in the format specified for wait()

In this case 0 is the return value of the ls command which means that the command was successful. The system function does not capture the stdout or stderr.

If you want to capture them, please use the subprocess module.

tuxtimo
  • 2,730
  • 20
  • 29
0

It returns 0 as that is the exit code for the command (meaning it exited cleanly).

If you want the results from a command, I would recommend using the subprocess module (https://docs.python.org/2/library/subprocess.html#module-subprocess).

Zakk L.
  • 208
  • 2
  • 5
0

It is the ls exit code.

If you execute an invalid command, the response will be probably something different than zero.

>>> os.system("ls -wk")
ls: invalid line width: k
512
iurisilvio
  • 4,868
  • 1
  • 30
  • 36