Search code examples
pythonpython-3.xsubprocesspopenls

List only files and directory names from subprocess ls -l


In python subprocess using Popen or check_output, I need to list files and directories in a given source directory. But I can only use the command ls -l.

Sample code

cmd = ["ls", "-l", source]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
exitcode = proc.returncode

if exitcode != 0:
    raise SystemError("Exitcode '{}', stderr: '{}', stdout: '{}'  for command: '{}'".format(
        exitcode, stderr, stdout, cmd))

From above proc, by using grep or any other way, can I get only a list of files and directory names inside source directory without other information?


Solution

  • If you insist on using subprocess please try:

    [x.split(' ')[-1] for x in stdout.decode().split('\n')[1:-1]]
    

    Obviously this is a pretty "hacky" way of doing this. Instead I can suggest the standard library glob

    import glob
    glob.glob(source + '/*')
    

    returns a list of all file/directory names in source.

    Edit:

    cmd = ["ls", source]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    exitcode = proc.returncode
    stdout.decode("utf-8").split('\n')[:-1]
    

    Should also do it. -l option is not necessary here.