473,803 Members | 2,038 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An optparse question

T
I have a short program using optparse.Option Parser that prints out help
message with -h flag:

% myprog.py -h
usage: myprog.py [options] input_file

options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file
My question is, is there a way to print a blank line (or any string)
before "usage: myprog.py [options] input_file" ? I tried using
callbacks without success. I think somehow I need to modify the
behavior of optparse.Option Parser.print_us age() function?

Jul 21 '06 #1
8 3531

T wrote:
I have a short program using optparse.Option Parser that prints out help
message with -h flag:

% myprog.py -h
usage: myprog.py [options] input_file

options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file
My question is, is there a way to print a blank line (or any string)
before "usage: myprog.py [options] input_file" ? I tried using
callbacks without success. I think somehow I need to modify the
behavior of optparse.Option Parser.print_us age() function?
you can make the usage line anything you want.

....
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(u sage=usage)
parser.print_he lp()
....

Jul 21 '06 #2
T
fuzzylollipop wrote:
>
you can make the usage line anything you want.

...
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(u sage=usage)
parser.print_he lp()
...
No, that affects the string printed only *after* the "usage = " string.
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
************ THIS IS NEWLY INSERTED STRING ************
usage: myprog.py [options] input_file
options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file

Jul 21 '06 #3
No, that affects the string printed only *after* the "usage = " string.
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:
The example was fine (except for a typo) as far as demonstrating the
concept. Try this corrected version:

from optparse import OptionParser

usage = '************ THIS IS NEWLY INSERTED STRING
************\nu sage: %prog [options] input_file'
parser = OptionParser(us age=usage)
parser.print_he lp()

Jul 21 '06 #4
T wrote:
fuzzylollipop wrote:

you can make the usage line anything you want.

...
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(u sage=usage)
parser.print_he lp()
...

No, that affects the string printed only *after* the "usage = " string.
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
************ THIS IS NEWLY INSERTED STRING ************
usage: myprog.py [options] input_file
options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file
It's possible, but it ain't easy:

from optparse import OptionParser, _, IndentedHelpFor matter

class MyFormatter(Ind entedHelpFormat ter):
pre_usage = "Hi there!\n"
def format_usage(se lf, usage):
return _("%susage: %s\n") % (self.pre_usage , usage)

parser = OptionParser(fo rmatter=MyForma tter())
The above filthy hack will print "Hi there!" before the usual usage
message.

Jul 21 '06 #5
dan.g...@gmail. com wrote:
No, that affects the string printed only *after* the "usage = " string.
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

The example was fine (except for a typo) as far as demonstrating the
concept. Try this corrected version:

from optparse import OptionParser

usage = '************ THIS IS NEWLY INSERTED STRING
************\nu sage: %prog [options] input_file'
parser = OptionParser(us age=usage)
parser.print_he lp()
Nope. That only *nearly* does what T wants. The usage message will
still be printed immediately *after* the 'usage: ' string.
>>parser = OptionParser(us age=usage)
parser.print_ help()
usage: ************ THIS IS NEWLY INSERTED STRING********* ***
usage: lopts.py [options] input_file

options:
-h, --help show this help message and exit
I had the same problem, and in order to get something printed before
the usage message, I found one easy-ish way was to subclass the
Formatter passed in to the Parser.

IMHO, optparse does a tricky task well, but it's implemented in a hard
to follow, inflexible manner. My "favorite" pet peeve is that the
options "dictionary " it returns isn't a dict. I wound up doing this to
it to get something [I considered] useful:

o, a = parser.parse_ar gs()
o = o.__dict__.copy ()
Peace,
~Simon

Jul 21 '06 #6
T wrote:
fuzzylollipop wrote:
>>you can make the usage line anything you want.

...
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(u sage=usage)
parser.print_ help()
...


No, that affects the string printed only *after* the "usage = " string.
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
************ THIS IS NEWLY INSERTED STRING ************
usage: myprog.py [options] input_file
options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file
Do a Google search for "monkey patching". You probably want to
monkey-patch the class's usage method.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jul 21 '06 #7
Nope. That only *nearly* does what T wants. The usage message will
still be printed immediately *after* the 'usage: ' string.
>parser = OptionParser(us age=usage)
parser.print_h elp()
usage: ************ THIS IS NEWLY INSERTED STRING********* ***
usage: lopts.py [options] input_file

options:
-h, --help show this help message and exit
Yes, I see what T meant now. Behavior expectations (assumptions) has a
way of clouding one's vision.

Thanks

Jul 21 '06 #8
"T" <ty*****@yahoo. comwrites:
[...]
What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
************ THIS IS NEWLY INSERTED STRING ************
usage: myprog.py [options] input_file
options:
-h, --help show this help message and exit
-v, --verbose print program's version number and exit
-o FILE Output file
HelpFormatter is what you need. Seems undocumented in the official
docs, but doesn't look risky to use (famous last words). Seems just
that nobody got around to documenting it.

import optparse

class NonstandardHelp Formatter(optpa rse.HelpFormatt er):

def __init__(self,
indent_incremen t=2,
max_help_positi on=24,
width=None,
short_first=1):
optparse.HelpFo rmatter.__init_ _(
self, indent_incremen t, max_help_positi on, width, short_first)

def format_usage(se lf, usage):
return "********** ** THIS IS NEWLY INSERTED STRING ************\nu sage: %s\n" % usage

def format_heading( self, heading):
return "%*s%s:\n" % (self.current_i ndent, "", heading)

parser = optparse.Option Parser(
usage="%prog [options] input_file",
formatter=Nonst andardHelpForma tter())
parser.parse_ar gs()
John
Jul 21 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2311
by: Hans-Joachim Widmaier | last post by:
I was really pleased when the Optik module found its way into the standard Python battery compartment, as it matched all my option parsing requirements. But, as always, there's really nothing that does all you ever want, especially when it comes to option parsing - there's just too many schemes to handle them all comfortably. With this program I'm working on, I started to recognize that not only the functionality should be delegated to...
3
3168
by: washu | last post by:
Hi, I'm was going through the module help located on http://docs.python.org/lib/optparse-store-action.html and I tried modifying it a tiny bit and things don't work. If someone could tell me what I'm doing wrong, I'd appreciate it. The script that works (based on the code on the webpage) is: #!/usr/bin/env python
5
1945
by: GMTaglia | last post by:
Hi guys, I was wondering why optparse accept an option if in the command line is not *exactly* the one present in the source code....may be an example will explain better.... #!/usr/bin/env python import optparse as opt
7
2793
by: Henry Ludemann | last post by:
I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. It allows you to easily creating command line interfaces to existing functions, using flags (which are optional) and arguments. It will automatically print a nicely formatted usage (eg: -h or --help), and easily & automatically validates parameter existence and type. You can download it, and read a bit more about it,...
3
2469
by: Tomi Silander | last post by:
Hi, this must have been asked 1000 times (or nobody is as stupid as me), but since I could not find the answer, here is the question. My program mitvit.py: -------------- import optparse optparse.OptionParser().parse_args() -------------- gives me
3
2461
by: Karlo Lozovina | last post by:
If I create a file with only one line: --- from optparse import OptionParser --- I get this when I try to run it from "DOS" prompt: Traceback (most recent call last): File "optparse.py", line 1, in ?
3
2808
by: Bob | last post by:
I'd like to setup command line switches that are dependent on other switches, similar to what rpm does listed below. From the grammar below we see that the "query-options" are dependent on the query switch, {-q|--query}. Can "optparse" do this or do I have to code my own "thing"? Thanks. QUERYING AND VERIFYING PACKAGES: rpm {-q|--query} .... query-options
0
1140
by: Steven Bethard | last post by:
I feel like I must be reinventing the wheel here, so I figured I'd post to see what other people have been doing for this. In general, I love the optparse interface, but it doesn't do any checks on the arguments. I've coded something along the following lines a number of times: class OptionArgParser(optparse.OptionParser): def __init__(self, *args, **kwargs): self.min_args = kwargs.pop('min_args', None) self.max_args =...
0
928
by: Robert Kern | last post by:
Jeff Keasler wrote: If you code it up with unit tests and documentation, it has a good chance. But in the meantime, you can tell optparse to stop processing options using the standard "--" marker. For example: $ cat mycommand.py import optparse parser = optparse.OptionParser()
0
9699
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9562
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10542
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10309
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10289
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9119
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6840
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4274
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3795
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.