How can I pass filenames with spaces as arguments?

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)


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.


I think the glob answer above is best, but xargs and find is also a solution that can be used sometimes.

find /some/dir/ -name '*.jpg' -print0 | xargs -0 python script.py

This works because -print0 on find will separate the output with null bytes rather than spaces, and the -0 on the xargs command line will assume the input is separated by null bytes.