0

I really need a list out of a system call such as os.system('ls ' + input) I've tried googling of course, but didn't find much.

Also tried different ways of coding it but I cannot get it to work.

import os

user_input = input("Specify directory: ")
directory = os.system('ls ' + str(user_input))
------------------------------------------------------------------
# I need a list made out of the directory variable.
# Also note that subprocessing doesn't work that well as it doesn't accept # bash special chars like '~/', whereas os.system() accepts that.
# What os.system(), subprocess.call() return is just a normal output and I # cannot get to list that.
# Also I have gotten my program to work with os.listdir() but os.listdir() # doesn't accept special chars like '~/'.

Obviously I would greatly appreciate it if somebody could give me a hand with this problem.

Thanks.

  • There are better ways to list out the files in a directory, do you really need to use `ls`? – Sayse May 01 '19 at 08:11
  • `directory.split()`? – Netwave May 01 '19 at 08:11
  • @Sayse, thanks for the reply. What do you suggest? –  May 01 '19 at 08:12
  • 2
    Possible duplicate of [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – Sayse May 01 '19 at 08:13
  • @Netwave, for some reason that doesn't work as I have tried it several times. Thanks though. –  May 01 '19 at 08:13
  • @Sayse, I already tried os.listdir(), the problem is that it doesn't comply with special shell chars like '~/' or '~/path/to/file/' –  May 01 '19 at 08:14
  • https://stackoverflow.com/q/2057045/1324033 – Sayse May 01 '19 at 08:17

1 Answers1

1

You can handle ~ in the input. And ., .. too.

os.listdir(os.path.abspath(os.path.expanduser(user_input)))

Ref: https://docs.python.org/2/library/os.path.html#os.path.expanduser

https://docs.python.org/2/library/os.path.html#os.path.abspath

rdas
  • 20,604
  • 6
  • 33
  • 46