Prevent expansion of wildcards in non-quoted python script argument when running in UNIX environment

Viewed 1335

I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

#!/usr/bin/env python

import argparse
import glob 

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)

In this case, everything works great if the user adds quotes to the passed argument like so:

./test_script.py -i "foo*.txt"

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?

5 Answers

Here is an example for the Bash shell that shows what @Tom Wyllie is talking about:

 alias sea='set -f; search_function' 
 search_function() { perl /home/scripts/search.pl $@ ; set +f; } 

This defines an alias called "sea" that:

  1. Turns off expansion ("set -f")
  2. Runs the search_function function which is a perl script
  3. Turns expansion back on ("set +f")

The problem with this is that if a user stops execution with ^C or some such then the expansion may not be turned back on leaving the user puzzling why "ls *" is not working. So I'm not necessarily advocating using this. :).

This worked for me:

files = sys.argv[1:]

Even though only one string is on the command line, the shell expands the wildcards and fills sys.argv[] with the list.

Related