How to pass Python command line options (vs arguments) when running script directly vs via Python interpreter?

David Raymond David.Raymond at tomtom.com
Wed Aug 15 14:13:00 EDT 2018


So what are you saying is an option vs an argument? Because I see no distinction whatsoever. When you run something you give it a bunch of strings.

That's it.

There is nothing magical about putting a dash in front of a letter, nothing magical about putting in a string that might possibly also be a file name. The only things that might matter are white space and quote characters, because really all you're doing is giving the shell or OS a <single> string, and it decides what to run and what is the resulting (ordered) list of strings which it will then pass to that program.

Being able to just run "script.py" is just a convenience provided by the OS. It goes "ohh, after I've parsed it, that first token matches up with an existing file, and my records say that that extension can be opened with this python.exe program, so I'm just gonna run that python.exe thing and pass it the ordered list of everything I just got."

In this specific case, the people who wrote python.exe decided that when it goes through the list of strings which it was given, that that first thing that doesn't start with a dash is the "file name", that anything before that "file name" are things it will look at right now, and anything after the "file name" are things it will throw into sys.argv and let later execution decide what to do with.

Since the convenience method uses the first bit as the "file name" to determine which convenience program to run, and the python.exe program just tosses anything after the "file name" into sys.argv, then to get anything as an "argument" to python.exe and not the script, then you either need to run it as "python.exe bunch of strings to pass to python.exe", or the more difficult method of "muck about with the OS's convenience method to get it to do something magical."


-----Original Message-----
From: Python-list [mailto:python-list-bounces+david.raymond=tomtom.com at python.org] On Behalf Of Malcolm Greene
Sent: Tuesday, August 14, 2018 7:47 PM
To: python-list at python.org
Subject: Re: How to pass Python command line options (vs arguments) when running script directly vs via Python interpreter?

> You might try:
> from getopt import getopt
> or the (apparently newer):
> from optparse import OptionParser

Thanks Mike. My question was trying to make a distinction between Python options (flags that precede the script or module name) and arguments (the script specific values passed on the command line following the script's name).

Here's a description of the options I'm referring to:
https://docs.python.org/3/using/cmdline.html#generic-options
-- 
https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list