473,326 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

What is the best way to print the usage string ?

Hi all,

I had to write a small script, and I did it in python instead of
shell-script. My script takes some arguments from the command line,
like this.

import sys
args = sys.argv[1:]
if args == []:
print """Concat: concatenates the arguments with a colon (:) between them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a.jar:b.jar:c/\""""
sys.exit(1)
print reduce(lambda x, y: x + ':' + y, sys.argv[1:])

Notice that the string messes the indentation in my script. The
indentation is correct, and if the script is invoked without
arguments, the usage string is printed correctly.

Now, how can I achieve the same result while keeping a clean
indentation ? How is this done in python world ? In C, I would do
this:

;; This buffer is for notes you don't want to save, and for Lisp evaluation.
;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

if (argc < N) {
printf("Usage: blah blah blah\n"
"Some more lines in the usage text\n"
"Some more lines here too\n");
exit(1);
}

The whitespace at the beginning of the string helps me keep the
indentation clean, and the construct "a" "b" is syntactic sugar that
allows me to create a large string without concatenating them at
runtime.

How can I get this in Python ?

[]'s
Leonel
Aug 3 '06 #1
7 7523
Leonel Gayard wrote:
>
Notice that the string messes the indentation in my script. The
indentation is correct, and if the script is invoked without
arguments, the usage string is printed correctly.

Now, how can I achieve the same result while keeping a clean
indentation ? How is this done in python world ? In C, I would do
this:
The whitespace at the beginning of the string helps me keep the
indentation clean, and the construct "a" "b" is syntactic sugar that
allows me to create a large string without concatenating them at
runtime.

How can I get this in Python ?
Not sure exactly what you are after, but it sounds like you need the
textwrap module:

http://docs.python.org/lib/module-textwrap.html

Or look at string formatting opeartions

http://docs.python.org/lib/typesseq-strings.html

rd

:

Aug 3 '06 #2
Leonel Gayard wrote:
Notice that the string messes the indentation in my script. The
indentation is correct, and if the script is invoked without
arguments, the usage string is printed correctly.

Now, how can I achieve the same result while keeping a clean
indentation ? How is this done in python world ? In C, I would do
this:

;; This buffer is for notes you don't want to save, and for Lisp
evaluation. ;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

if (argc < N) {
printf("Usage: blah blah blah\n"
"Some more lines in the usage text\n"
"Some more lines here too\n");
exit(1);
}

The whitespace at the beginning of the string helps me keep the
indentation clean, and the construct "a" "b" is syntactic sugar that
allows me to create a large string without concatenating them at
runtime.

How can I get this in Python ?
>>print ("You can do that in Python too.\n"
.... "Personally, though,\n"
.... "I wouldn't bother.")
You can do that in Python too.
Personally, though,
I wouldn't bother.

Like in C, you get a single string:
>>"a" "b"
'ab'

The parentheses are just there to allow you to spread that string over
multiple lines.

Peter

Aug 3 '06 #3
Leonel Gayard wrote:
Hi all,

I had to write a small script, and I did it in python instead of
shell-script. My script takes some arguments from the command line,
like this.

import sys
args = sys.argv[1:]
if args == []:
print """Concat: concatenates the arguments with a colon (:) between them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a.jar:b.jar:c/\""""
sys.exit(1)
print reduce(lambda x, y: x + ':' + y, sys.argv[1:])

Notice that the string messes the indentation in my script. The
indentation is correct, and if the script is invoked without
arguments, the usage string is printed correctly.

Now, how can I achieve the same result while keeping a clean
indentation ? How is this done in python world ? In C, I would do
this:

;; This buffer is for notes you don't want to save, and for Lisp evaluation.
;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

if (argc < N) {
printf("Usage: blah blah blah\n"
"Some more lines in the usage text\n"
"Some more lines here too\n");
exit(1);
}

The whitespace at the beginning of the string helps me keep the
indentation clean, and the construct "a" "b" is syntactic sugar that
allows me to create a large string without concatenating them at
runtime.

How can I get this in Python ?

[]'s
Leonel
Python also concatenates adjacent strings, but the "real" newlines
between your strings will need to be escaped (otherwise, because the
newlines are statement separators, you will have one print statement
followed by string literals with the wrong indentation.)

print "Usage: blah blah blah\n" \
"Some more lines in the usage text\n" \
"Some more lines here too."

(Note that the final string literal newline is not needed since print
will add one of it's own.)

HTH,
~Simon

Aug 3 '06 #4
Leonel Gayard wrote:
Hi all,

I had to write a small script, and I did it in python instead of
shell-script. My script takes some arguments from the command line,
like this.

import sys
args = sys.argv[1:]
if args == []:
print """Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a.jar:b.jar:c/\""""
sys.exit(1)
print reduce(lambda x, y: x + ':' + y, sys.argv[1:])

Notice that the string messes the indentation in my script. The
indentation is correct, and if the script is invoked without
arguments, the usage string is printed correctly.

Now, how can I achieve the same result while keeping a clean
indentation ? How is this done in python world ? In C, I would do
this:

;; This buffer is for notes you don't want to save, and for Lisp
evaluation.
;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

if (argc < N) {
printf("Usage: blah blah blah\n"
"Some more lines in the usage text\n"
"Some more lines here too\n");
exit(1);
}

The whitespace at the beginning of the string helps me keep the
indentation clean, and the construct "a" "b" is syntactic sugar that
allows me to create a large string without concatenating them at
runtime.

How can I get this in Python ?
Quite close:
>>args = []
if not args:
.... print "line 1\n" \
.... "line 2\n" \
.... "line 3\n" \
....
....
line 1
line 2
line 3

But this is somehow ugly... the textwrapper module may be a better
solution. Or if you don't plan on making the script a module, you could
use the docstring:

bruno@bousin ~ $ cat ~/playground/concat.py
# !/usr/bin/python
"""
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a:b:c/\
"""

import sys
args = sys.argv[1:]
if not args:
sys.exit(globals()['__doc__'].strip())
print reduce(lambda x, y: x + ':' + y, args)

bruno@bousin ~ $ python ~/playground/concat.py
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints "a:b:c/
bruno@bousin ~ $ python ~/playground/concat.py a b c
a:b:c
bruno@bousin ~ $


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 3 '06 #5
Leonel Gayard wrote:
Hi all,

I had to write a small script, and I did it in python instead of
shell-script. My script takes some arguments from the command line,
like this.

import sys
args = sys.argv[1:]
if args == []:
print """Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a.jar:b.jar:c/\""""
sys.exit(1)
print reduce(lambda x, y: x + ':' + y, sys.argv[1:])
The short answer is to use textwrap.dedent::
>>import textwrap
if True:
.... print textwrap.dedent('''\
.... Concat: concatenates the arguments with a colon (:) between
.... them
.... Usage: concat arg1 [arg2...]
.... Example: concat a b c prints "a.jar:b.jar:c/"''')
....
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints "a.jar:b.jar:c/"
You also might consider using an argument parsing like argparse[1] to
build your usage string for you:

------------------------------ concat.py ------------------------------
import argparse

if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='concatenates the arguments with a colon (:) '
'between them')
parser.add_argument('args', metavar='arg', nargs='+',
help='one item to be concatenated')
namespace = parser.parse_args()
print ':'.join(namespace.args)
-----------------------------------------------------------------------
$ concat.py
usage: concat.py [-h] arg [arg ...]
concat.py: error: too few arguments

$ concat.py -h
usage: concat.py [-h] arg [arg ...]

concatenates the arguments with a colon (:) between them

positional arguments:
arg one item to be concatenated

optional arguments:
-h, --help show this help message and exit

$ concat.py a b c
Steve

[1] http://argparse.python-hosting.com/
Aug 3 '06 #6
There's been a good lot of response to the problem originally stated,
but no-one's pointed out that:
>print reduce(lambda x, y: x + ':' + y, sys.argv[1:])
is a confusing (and slow) way of writing:

print ':'.join(sys.argv[1:])

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Aug 4 '06 #7
In article <11**********************@p79g2000cwp.googlegroups .com>,
"Simon Forman" <ro*********@yahoo.comwrote:
...
Python also concatenates adjacent strings, but the "real" newlines
between your strings will need to be escaped (otherwise, because the
newlines are statement separators, you will have one print statement
followed by string literals with the wrong indentation.)

print "Usage: blah blah blah\n" \
"Some more lines in the usage text\n" \
"Some more lines here too."

(Note that the final string literal newline is not needed since print
will add one of it's own.)
One can also use parentheses:

print ( "Usage: blah blah blah\n"
"Some more lines in the usage text\n"
"Some more lines here too." )

The newlines in the string are still needed, but the ones escaping the
EOLs are not.
__________________________________________________ ______________________
TonyN.:' *firstname*nlsnews@georgea*lastname*.com
' <http://www.georgeanelson.com/>
Aug 5 '06 #8

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

Similar topics

15
by: lkrubner | last post by:
I want to give users the power to edit files from an easy interface, so I create a form and a PHP script called "fileUpdate". It does a reasonable about of error checking and prints out some...
220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
2
by: vincent delft | last post by:
I want to write a script that will monitore the performance of a web application delivering HTTP and HTTPS pages. I would like to know the best way to do it... By reading Python Doc. I've...
8
by: Joe | last post by:
I'm using Python 2.4 on Windows XP SP2. I'm trying to receive a command line argument that is a newline (\n) Here is the command line to use sample.py "\n" Here is a sample.py script
13
by: deko | last post by:
I use this convention frequently: Exit_Here: Exit Sub HandleErr: Select Case Err.Number Case 3163 Resume Next Case 3376 Resume Next
51
by: jacob navia | last post by:
I would like to add at the beginning of the C tutorial I am writing a short blurb about what "types" are. I came up with the following text. Please can you comment? Did I miss something? Is...
41
by: Mountain Bikn' Guy | last post by:
What is the current preferred way to save user preferences in dotnet? Is the registry the right place to do this? Can anyone recommend a good article (or book) for this topic? Thanks.
8
by: werner | last post by:
Hi! I don't want to use eval() in order to parse a user-supplied formula. What alternatives do I have? PHP has no standard functionality for tokenizing or parsing expressions in this regard. ...
14
by: howa | last post by:
void reverse_string(char *str) { if (str == NULL) return; char tmp; size_t len = strlen(str); size_t mid = (int) len / 2; for (size_t i = 0; i < mid; i++) {
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.