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)

  • You should quote the shell expansion: "$(ls -Q '/some/dir/*.jpg')". However there are better alternatives as stated by the answers. – Bakuriu Aug 17 '16 at 12:59

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.