0

i need help understanding why i cant iterate through the ls -ltcrd output which im storing in a variable:

def test():
    tmplist = os.system('ls -ltcrd /tmp/*')
    tmplist.split(' ')[:1]  #trying to grab the last column here

print test()

What I'm trying to do with the above python code is equivalent to this in shell:

ls -ltcrd /tmp/* | awk '{print $NF}'

Note that the output contains the absolute path of all the files under /tmp.

Ideally, Id like to avoid calling any external utilities. But running it as shown above seems to be the simplest way to get what i want.

not even sure if "iteration" is the right term to use to describe this.

RoyMWell
  • 199
  • 1
  • 9
  • Your function `test` returns `None` because there is no `return` statement – Michael H. Jul 21 '18 at 17:39
  • Read the documentation for [`os.system`](https://docs.python.org/3/library/os.html#os.system). It returns the exit code of the command. – Patrick Haugh Jul 21 '18 at 17:40
  • 2
    Also, `[:1]` grabs the **first** element, not the last – DeepSpace Jul 21 '18 at 17:41
  • @PatrickHaugh and is deprecated.. – DeepSpace Jul 21 '18 at 17:41
  • 1
    There are other functions in the `os` module that can, for instance, list directories. – David Maze Jul 21 '18 at 17:42
  • You want my opinion? There will surely be people now who describe os.system as unsafe. But subprocess.Popen and all that stuff is too complicated for me. Look here, if you want to pass insecure user input to os.system: https://stackoverflow.com/a/847800/1707015 ;) – qräbnö Jul 21 '18 at 17:45

1 Answers1

2

Try something like this...

import subprocess
import os

# use the subprocess module to get the output of the command
def test(path):
    tmplist = subprocess.check_output(['ls', '-ltcrd', path])
    return tmplist.split()[-1:][0]

# get every filename under /tmp/
files = os.listdir('/tmp/')

# iterate over every filename, and run 'test'
for file in files:
    x = test('/tmp/' + file)
    print(x)
wg4568
  • 319
  • 4
  • 15