What's the correct way to handle Unix style wildcard arguments using optparse
in Python? I have:
myscript.py:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--input", dest="input", default=None, nargs=1)
parser.add_option("--outdir", dest="outdir", default=None, nargs=1)
(options, args) = parser.parse_args()
I want to be able to do:
myscript.py --input *.txt --outdir mydir/
I don't want to necessarily read the contents of all the files matching *.txt
. I want myscript.py
to access their filenames, because some scripts just pass on the filenames to other programs without needing to open/read the files. How can I get an iterator that returns the filenames, while still allowing other arguments like --outdir
to be passed after the wildcard friendly option (in this case --input
)? thanks.
Unix shells will expand *.txt
into separate arguments before they are passed to your program; Windows' command interpreter will not.
Assuming you're using an environment where they aren't expanded first -- that is, invoking python prog.py '*.txt'
, for instance, you can use glob.glob() to do the expansion yourself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.