Popen Question

Ian ian.g.kelly at gmail.com
Mon Nov 8 19:49:44 EST 2010


On Nov 8, 3:35 pm, Hans Mulder <han... at xs4all.nl> wrote:
> > Perhaps this example better demonstrates what is going on:
>
> >>>> p = subprocess.Popen(['echo one $0 three $1 five', 'two', 'four'],
> > ...                      shell=True)
> > one two three four five
>
> Maybe I'm thick, but I still don't understand.  If I run a shell script,
> then the name of the script is in $0 and the first positional arguments
> is in $1, similar to how Python sets up sys.argv.
>
> But in this case the first positional argument is in $0.  Why is that?

It's just a quirk in the way the shell handles the -c option.  The
syntax for the shell invocation boils down to something like this:

sh [-c command_string] command_name arg1 arg2 arg3 ...

Without the -c option, sh runs the file indicated by command_name,
setting $0 to command_name, $1 to arg1, $2 to arg2, etc.

With the -c option, it does the same thing; it just runs the
command_string instead of a file pointed to by command_name.  The
latter still conceptually exists as an argument, however, which is why
it still gets stored in $0 instead of $1.

We could argue about whether this approach is correct or not, but it's
what the shell does, and that's not likely to change.

Cheers,
Ian



More information about the Python-list mailing list