473,391 Members | 1,477 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,391 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 7528
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.