Search code examples
pythonparsingargv

Passing list argument without quotes to a script


A Python script treats each command-line argument passed to it as string. Ideally we should use some standard parser to parse command line arguments but I was trying sys.argv

If we use sys.argv to parse following arguments:

/usr/local/bin/somemodule 1.2.3.4 11.22.33.44 111.222.333.444 1.2.3.4 [1.2.3.4,1.2.3.4] [sub.domain.com,sub2.domain.com,sub3.domain.com] somestring

When I print sys.argv[1:] I get below list with one extra argument

['1.2.3.4', '11.22.33.44', '111.222.333.444', '1.2.3.4', '1', '1', '2', 'somestring'

This behaviour is not consistent. Any idea why the list gets converted to '1'?


Solution

  • Without quoting, [string] is a shell wildcard which matches files whose name is s or t or r or i or n or g.

    Apparently you have a file named 1 in the current directory, and the real wildcard you tried to use matched it.

    This can be hard to diagnose or reproduce because the shell (in its default configuration on most platforms) will pass through the wildcard verbatim if there are no matching files.

    The lesson is to basically always quote shell expressions which contain nontrivial strings.