Ubuntu – How to pass filenames with spaces as arguments

bashcommand linepython

I have a Python script which accepts string arguments.

$ python script.py "one image.jpg" "another image.jpg"

This works as expected.

Python argparse: ["one image.jpg", "another image.jpg"]


If I need to pass filenames I would do,

$ python script.py $(ls "/some/dir/*.jpg")

Python argparse: ["one", "image.jpg", "another", "image.jpg"]

If use the -Q of ls command, I can wrap results between double quotes. However, quotes stay escaped in Python script, ie.

$ python script.py $(ls -Q "/some/dir/*.jpg")

Python argparse: ['"one image.jpg"', '"another image.jpg"']


How should I expand ls filenames into proper strings to use as arguments? (as in my very first example)

Best Answer

Don't parse ls. Just use:

python script.py /path/to/*.jpg

This performs shell globbing which replaces /path/to/*.jpg by the proper list.