[Tutor] Fwd: Simple copy script

2008-04-14 Thread Que Prime
This is what I came up with after writing it out and reading the
corresponding functions.  I feel I'm close but something is still awry.


#file copy based on input file containing filenames to be copied

##
import os
import shutil

os.chdir('c:\\test')
infile = open(input.txt,r)

for line in infile:
  shutil.copy(line, 'outfolder')
  #print line 'copied'
infile.close()

#

-- Forwarded message --
From: Alan Gauld [EMAIL PROTECTED]
Date: Sat, Apr 12, 2008 at 5:15 AM
Subject: Re: [Tutor] Simple copy script
To: tutor@python.org


Que Prime [EMAIL PROTECTED] wrote

 I'm trying to copy files from one directory to another based on an
 input txt
 file containing the filename.

 Source directory = C:\test
 Destination directory = C:\output

 input.txt looks like:

 12345.pdf
 12344.pdf

Try writing what you want to do in structured English first

Open the file input.txt
For each line in input.txt :
 copy the named file from source to destination
Close the file input.txt

Now can you write that ion Python? (You may want to check
the shutil module for copying the files)

If you can';t get it to work send us your code and any error
messages you get.

You will find more detailed info in the Using the OS
topic of my tutor.

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Simple copy script

2008-04-14 Thread Andreas Kostyrka
line.strip()

for line in file: = line will contain '\n' at the end of the string.

Andreas

Am Montag, den 14.04.2008, 00:08 -0700 schrieb Que Prime:
 
 This is what I came up with after writing it out and reading the
 corresponding functions.  I feel I'm close but something is still
 awry.
 
 
 #file copy based on input file containing filenames to be copied
 
 ##
 import os
 import shutil
 
 os.chdir('c:\\test')
 infile = open(input.txt,r)
 
 for line in infile:
   shutil.copy(line, 'outfolder')
   #print line 'copied'
 infile.close()
 
 #
 
 -- Forwarded message --
 From: Alan Gauld [EMAIL PROTECTED]
 Date: Sat, Apr 12, 2008 at 5:15 AM
 Subject: Re: [Tutor] Simple copy script
 To: tutor@python.org
 
 
 Que Prime [EMAIL PROTECTED] wrote
 
 
  I'm trying to copy files from one directory to another based on an
  input txt
  file containing the filename.
 
  Source directory = C:\test
  Destination directory = C:\output
 
  input.txt looks like:
 
  12345.pdf
  12344.pdf
 
 
 Try writing what you want to do in structured English first
 
 Open the file input.txt
 For each line in input.txt :
  copy the named file from source to destination
 Close the file input.txt
 
 Now can you write that ion Python? (You may want to check
 the shutil module for copying the files)
 
 If you can';t get it to work send us your code and any error
 messages you get.
 
 You will find more detailed info in the Using the OS
 topic of my tutor.
 
 --
 Alan Gauld
 Author of the Learn to Program web site
 http://www.freenetpages.co.uk/hp/alan.gauld
 
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple copy script

2008-04-14 Thread Alan Gauld

Que Prime [EMAIL PROTECTED] wrote

 This is what I came up with after writing it out and reading the
 corresponding functions.  I feel I'm close but something is still 
 awry.

You need to give us more information.
What is still awry? Do you get any errors or is it not
copyng all files? Or any of them?

Here are some possibilities:

Do all the files you are copying exist? - Are you 100% sure?
Does the 'outfile' folder exist? Does it exist inside C:\test?

To try and fix things:

Add some print lines to print:
1) The current folder( use os.getcwd() )
2) Each filename
3) A directory listing of outfile after copying the files

Finally a couple of comments:

 #file copy based on input file containing filenames to be copied

 ##
 import os
 import shutil

 os.chdir('c:\\test')
 infile = open(input.txt,r)

 for line in infile:

You can miss out the open() line by putting it into the for loop:

for line in open('input.txt','r'):

  shutil.copy(line, 'outfolder')

You may want to strip() the line first just in case any extra
whitespace has been added in the file


  #print line 'copied'
 infile.close()

HTH

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] encode unicode strings from pysqlite

2008-04-14 Thread Dinesh B Vadhia
Here is a program that SELECT's from a pysqlite database table and encode's the 
returned unicode strings:

import sys
import os
import sqlite3

con = sqlite3.connect(testDB.db)
cur = con.cursor()

a = u'99 Cycling Swords'
b = a.encode('utf-8')
print b

q = '%wor%'
limit = 25
query = SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s' %(q, 
limit)
for row in cur.execute(query):
r = str(row)
print r.encode('utf-8')


The print b results in: 99 Cycling Swords ... which is what I want.

But, the print r.encode('utf-8') leaves the strings as unicode strings eg. u'99 
Cycling Swords'

Any ideas what might be going on?

Dinesh




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] encode unicode strings from pysqlite

2008-04-14 Thread Kent Johnson
Dinesh B Vadhia wrote:
 Here is a program that SELECT's from a pysqlite database table and 
 encode's the returned unicode strings:

 query = SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s' 
 %(q, limit)
 for row in cur.execute(query):

Here row is a list containing a single unicode string. When you convert 
a list to a string, it converts the list elements to strings using the 
repr() function. The repr() of a unicode string includes the u'' as part 
of the result.

In [64]: row = [u'99 Cycling Swords']
In [65]: str(row)
Out[65]: [u'99 Cycling Swords']

Notice that the above is a string that includes u' as part of the string.

What you need to do is pick out the actual data and encode just that to 
a string.
In [62]: row[0].encode('utf-8')
Out[62]: '99 Cycling Swords'

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] encode unicode strings from pysqlite

2008-04-14 Thread Dinesh B Vadhia
Hi! Kent.  The row[0].encode('utf-8') works perfectly within a standalone 
program.  But didn't work within webpy until I realized that maybe webpy is 
storing the row as a dictionary (which it does) and that you have to get the 
string by the key (ie. 'fieldB').  That worked and also webpy encodes the 
unicode string at the same time.  Here are the details:

# standard Python: testDB.py
con = sqlite3.connect(testDB.db)
cur = con.cursor()
query = SELECT fieldB FROM testDB 
WHERE fieldB LIKE '%s' 
LIMIT '%s' %(q, limit)
for row in cur.execute(query):# row is a list
print row[0].encode('utf-8')# works perfectly!

# webpy: testDB2.py
web.config.db_parameters = dict(dbn='sqlite', db=testDB.db)
for row in web.select('testDB', 
what='fieldB', 
where='fieldB LIKE $q', 
limit=limit, 
vars={'q':q}):
r = row['fieldB']# get encode'd unicode through 
dict key value
print r   # works perfectly!




- Original Message - 
From: Kent Johnson 
To: Dinesh B Vadhia 
Cc: tutor@python.org 
Sent: Monday, April 14, 2008 3:42 AM
Subject: Re: [Tutor] encode unicode strings from pysqlite


Dinesh B Vadhia wrote:
 Here is a program that SELECT's from a pysqlite database table and 
 encode's the returned unicode strings:

 query = SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s' 
 %(q, limit)
 for row in cur.execute(query):

Here row is a list containing a single unicode string. When you convert 
a list to a string, it converts the list elements to strings using the 
repr() function. The repr() of a unicode string includes the u'' as part 
of the result.

In [64]: row = [u'99 Cycling Swords']
In [65]: str(row)
Out[65]: [u'99 Cycling Swords']

Notice that the above is a string that includes u' as part of the string.

What you need to do is pick out the actual data and encode just that to 
a string.
In [62]: row[0].encode('utf-8')
Out[62]: '99 Cycling Swords'

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Font capture from webpages

2008-04-14 Thread Ashish Sharma
Hi ,

I want to find the font style,Font size written in webpage without
looking into source code.

Can Any one tell if there is API avalable for this in python .

Thanks in Advance.
Ashish Sharma
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Font capture from webpages

2008-04-14 Thread W W
beautiful soup would do it. It's still looking into the source, though.

On Mon, Apr 14, 2008 at 7:02 AM, Ashish Sharma
[EMAIL PROTECTED] wrote:
 Hi ,

  I want to find the font style,Font size written in webpage without
  looking into source code.

  Can Any one tell if there is API avalable for this in python .

  Thanks in Advance.
  Ashish Sharma
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor




-- 
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Font capture from webpages

2008-04-14 Thread Kent Johnson
Ashish Sharma wrote:
 Hi ,
 
 I want to find the font style,Font size written in webpage without
 looking into source code.

Do you mean you don't want to look at the HTML/CSS for the page? If not, 
I guess you will have to somehow query the browser. Tools for that will 
be specific to the browser/OS you are using.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Programming Tools

2008-04-14 Thread bhaaluu
A (mainly Java) programmer on a LUG mailing list asks:

What is a good IDE [for Python] that has Python tools for:

library management,
code completion,
debugging,
documentation,
help

Since I'm not familiar with Java at all, I'm not sure how many
of the things he is asking for, are even relevant for Python?
I'm presuming he is working with a team, and is developing
complex programs.

What do _you use?
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 50, Issue 43

2008-04-14 Thread kinuthia muchane

 
 Message: 1
 Date: Mon, 14 Apr 2008 01:31:41 -0700
 From: Dinesh B Vadhia [EMAIL PROTECTED]
 Subject: [Tutor] encode unicode strings from pysqlite
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Here is a program that SELECT's from a pysqlite database table and encode's 
 the returned unicode strings:
 
 import sys
 import os
 import sqlite3
 
 con = sqlite3.connect(testDB.db)
 cur = con.cursor()
 
 a = u'99 Cycling Swords'
 b = a.encode('utf-8')
 print b
 
 q = '%wor%'
 limit = 25
 query = SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s' %(q, 
 limit)
 for row in cur.execute(query):
 r = str(row)
 print r.encode('utf-8')

Why not change this to:

 for row in cur.execute(query):
 for item in row:
   print item.encode('utf-8')
which will return a string ?


Kinuthia.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Programming Tools

2008-04-14 Thread Jordan Greenberg
bhaaluu wrote:
  A (mainly Java) programmer on a LUG mailing list asks:
 
  What is a good IDE [for Python] that has Python tools for:
 
  library management,
  code completion,
  debugging,
  documentation,
  help
 
  Since I'm not familiar with Java at all, I'm not sure how many
  of the things he is asking for, are even relevant for Python?
  I'm presuming he is working with a team, and is developing
  complex programs.
 
  What do _you use?

Personally, I use Emacs for more or less everything. As far as a more 
complete IDE solution goes, PyDev for the Eclipse platform is pretty 
popular. If you're willing to spend some $$$, then PyDev Extensions 
(also for Eclipse) are good, or ActiveState's Komodo IDE. They seem to 
be the gold standard.

-Jordan Greenberg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] input and output files from terminal

2008-04-14 Thread Brain Stormer
I have a python program which works fine when run using idle but I would
like call the program from the terminal.

python test.py -i inputfile -o outputfile

I tried with raw_input but that only works in idle.  Can this be achieved?
Thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread v2punkt0
look at the OptParse module, with this u can easily realize such things.
http://docs.python.org/lib/module-optparse.html


On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote:
 I have a python program which works fine when run using idle but I would
 like call the program from the terminal.
 
 python test.py -i inputfile -o outputfile
 
 I tried with raw_input but that only works in idle.  Can this be achieved?
 Thanks

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread linuxian iandsd
i think you need to try :

cat input.txt | /usr/bin/python test.py output.txt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Font capture from webpages

2008-04-14 Thread linuxian iandsd
 I want to find the font style,Font size written in webpage without looking
  into source code.
 



your best bet would be your eyes. otherwise python will need to parse the
source code to tell.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread bhaaluu
On Mon, Apr 14, 2008 at 12:55 PM, Brain Stormer [EMAIL PROTECTED] wrote:
 I have a python program which works fine when run using idle but I would
 like call the program from the terminal.

 python test.py -i inputfile -o outputfile

 I tried with raw_input but that only works in idle.  Can this be achieved?
  Thanks

 ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor

Please see:
http://www.faqs.org/docs/diveintopython/kgp_commandline.html

From the book: Dive into Python.
Source code examples from the book:
http://diveintopython.org/download/diveintopython-examples-4.1.zip

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pythonic way to extract delimited substrings

2008-04-14 Thread Malcolm Greene
Suggestions on the best way to extract delimited substrings strings from
a larger string?

Background: I have a long multi-line string with expressions delimited
with '(' and ')' markers. I would like to extract these substrings and
process them in a loop.

Because the left and right delimiters are different from each other
*and* multi-char strings, it would appear that the .split() method would
not be an appropriate tool for this work.

I know how to do this task with regular expressions, but I'm always
cautious about using a bazooka when a hammer will suffice.

What strategy would you recommend?

1. Write a simple parsing function using string primitives (find,
slicing)

2. Use regular expressions

3. Use a 3rd party string processing module

Thanks!
Malcolm

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Remove specific chars from a string

2008-04-14 Thread Malcolm Greene
What is the Pythonic way to remove specific chars from a string? The
.translate( table[, deletechars]) method seems the most 'politically
correct' and also the most complicated.

My ideas:

1. For each char to be removed, do a .replace( char_to_delete, '' )

2. Do a .split( str_of_chars_to_delete ) followed by a ''.join()

3. Use a regular expression

4. Other?

Thanks!
Malcolm
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread Brain Stormer
I used the optparse module since that is exactly what I wanted.  Here is my
code:

import sys
from optparse import OptionParser
import os

parser = OptionParser()
parser.add_option(-i, --input, dest=infile,
help=input FILE to convert, metavar=FILE)
parser.add_option(-o, --output, dest=outfile,
help=output FILE to convert to, metavar=FILE)
(options, args) = parser.parse_args()

if not os.path.isfile(options.infile):
print Input files does not exit...Quitting
sys.exit()
elif os.path.isfile(options.outfile):
print Output file exists, Remove it first
sys.exit()

Thanks everyone.


On Mon, Apr 14, 2008 at 1:14 PM, [EMAIL PROTECTED] wrote:

 look at the OptParse module, with this u can easily realize such things.
 http://docs.python.org/lib/module-optparse.html


 On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote:
  I have a python program which works fine when run using idle but I would
  like call the program from the terminal.
 
  python test.py -i inputfile -o outputfile
 
  I tried with raw_input but that only works in idle.  Can this be
 achieved?
  Thanks

  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Programming Tools

2008-04-14 Thread Alan Gauld

Jordan Greenberg [EMAIL PROTECTED] wrote

  What is a good IDE [for Python] that has Python tools for:
 
  library management,
  code completion,
  debugging,
  documentation,
  help

Depending on what he wants in the way of Library Management
then Pythonwin will give him all of that for free on Windows.

  Since I'm not familiar with Java at all, I'm not sure how many
  of the things he is asking for, are even relevant for Python?

They are all relevant but might have a slightly different meaning...

 complete IDE solution goes, PyDev for the Eclipse platform is pretty
 popular. If you're willing to spend some $$$, then PyDev Extensions
 (also for Eclipse) are good, or ActiveState's Komodo IDE. They seem 
 to
 be the gold standard.

I'd second that particularly since a Java programmer has
about a 50% chance of already using Eclipse so its an
easy continuation of what he already knows.

Platform independant but very resource hungry. But if he
uses it already thats not a problem.

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Font capture from webpages

2008-04-14 Thread Alan Gauld

Ashish Sharma [EMAIL PROTECTED] wrote 

 I want to find the font style,Font size written in webpage without
 looking into source code.

Do you mean you need to find the actual font used in the 
browser regardless of the settings in the HTML/CSS source?

On Windows you can probably do that by querying 
the OLE/DDE interface but it will be messy. On browsers 
like Lynx or Links it will be determined by the users resource 
file settings. 

It seems like a very strange thing to want to do.
HTML and CSS allow a lot of scope for the browser to 
interpret things like fonmts locally. For example if a 
page specifies Helvetica it could wind up being displayed 
on one browser as Helvetica and on another (on the same 
computer!) as Arial or even Courier...

 Can Any one tell if there is API avalable for this in python .

Not in Python as such. You have a choice of ways of 
parsing the HTML but querying the browser will need to 
go via things like COM or DDE I suspect. (And I have 
no idea what you'd do on Linux or MacOS!)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread Alan Gauld

Brain Stormer [EMAIL PROTECTED] wrote

I have a python program which works fine when run using idle but I 
would
 like call the program from the terminal.

 python test.py -i inputfile -o outputfile

Easier to use file redirection:

python test.py  inputfile  outputfile

The -i flag in particular might conflict with Pythons own -i option.

 I tried with raw_input but that only works in idle.

What makes you think that?
raw_input is the normal way to get input from stdin.

Can you explain what you did and what the result was?
Perhaps with a short code example?

Try this for example:



name = raw_input('What's your name? ')
print hello, name



That can be run in IDLE or in a command window
or using file redirection as described above.

Tell us how you get on...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic way to extract delimited substrings

2008-04-14 Thread Kent Johnson
Malcolm Greene wrote:
 Suggestions on the best way to extract delimited substrings strings from
 a larger string?
 
 Background: I have a long multi-line string with expressions delimited
 with '(' and ')' markers. I would like to extract these substrings and
 process them in a loop.

 What strategy would you recommend?

If you just want to get the text between ( and ), re.findall() or 
re.finditer() is probably the simplest way to do it. If it is more 
complicated than that (e.g. nesting, escape chars) then I would probably 
look at pyparsing.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-14 Thread Kent Johnson
Malcolm Greene wrote:
 What is the Pythonic way to remove specific chars from a string? The
 .translate( table[, deletechars]) method seems the most 'politically
 correct' and also the most complicated.

Most 'correct' and also by far the fastest. This recipe makes it a bit 
easier to use:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic way to extract delimited substrings

2008-04-14 Thread Alan Gauld

Malcolm Greene [EMAIL PROTECTED] wrote in

 Background: I have a long multi-line string with expressions 
 delimited
 with '(' and ')' markers. I would like to extract these substrings 
 and
 process them in a loop.

 I know how to do this task with regular expressions, but I'm always
 cautious about using a bazooka when a hammer will suffice.

Sounds like an ideal candidate for regex and findall to me.

If you have to stop a tank a bazooka may be the right tool...

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-14 Thread Alan Gauld

Malcolm Greene [EMAIL PROTECTED] wrote

 What is the Pythonic way to remove specific chars from a string? The
 .translate( table[, deletechars]) method seems the most 'politically
 correct' and also the most complicated.

Assuming you have lots of different characters and not just
one to remove, then: either translate()  or

 3. Use a regular expression

HTH,

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-14 Thread Dick Moores


At 12:04 PM 4/14/2008, Kent Johnson wrote:
Malcolm Greene wrote:
 What is the Pythonic way to remove specific chars from a string?
The
 .translate( table[, deletechars]) method seems the most
'politically
 correct' and also the most complicated.
Most 'correct' and also by far the fastest. This recipe makes it a bit

easier to use:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342

Just a couple of days ago I needed a function to determine the number of
significant digits in a real number. It also involves the removal of
specific chars from a string, but not all at once. (It ignores the
implicit assumption that the digits at the end of the remaining string
are actually significant.) This is what I came up with. It works, but
could it be improved? 
def sigDigits(n):
 
 Strips any real decimal (as string) to just its
significant digits,
 then returns its length, the number of significant
digits. 
 Examples: -345 - 345 -
3;
 3.000 - 3000 - 4
 0.0001234 - 1234 -
4;
 10.0001234 - 11234
- 9
 7.2345e+543 - 72345 -
5
 
 s = str(n).lstrip(-+0)
 s = s.lstrip(.)
 s = s.lstrip(0)
 s = s.lstrip(.)
 s = s.replace(., ) 
 if e in s:
 s =
s.rstrip(+-0123456789)
 s =
s.rstrip(e)
 return len(s)
Thanks,
Dick Moores



UliPad The Python Editor:

http://code.google.com/p/ulipad/


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-14 Thread Kent Johnson
Dick Moores wrote:
 def sigDigits(n):
 
 Strips any real decimal (as string) to just its significant digits,
 then returns its length, the number of significant digits.
 Examples: -345 - 345 - 3;
 3.000 - 3000 - 4
 0.0001234 - 1234 - 4;
 10.0001234 - 11234 - 9
 7.2345e+543 - 72345 - 5
 
 s = str(n).lstrip(-+0)
 s = s.lstrip(.)
 s = s.lstrip(0)
 s = s.lstrip(.)

Why the repeated strips? Couldn't this all just be done with 
lstrip('-+0.') ?

How many significant digits are in 123000?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Best practice: Use % operator or locale.format?

2008-04-14 Thread python
Does the % operator always respect locale or should one use
locale.format() instead?

Are there guidelines where one should use one string formatting
technique vs. another?

Thanks!
Malcolm
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-14 Thread Dick Moores


At 01:39 PM 4/14/2008, Kent Johnson wrote:
Dick Moores wrote:
def sigDigits(n):
 
 Strips any real decimal (as string) to just its
significant digits,
 then returns its length, the number of significant
digits.
 Examples: -345 - 345 -
3;
 3.000 - 3000 - 4
 0.0001234 - 1234 -
4;
 10.0001234 - 11234
- 9
 7.2345e+543 - 72345 -
5
 
 s = str(n).lstrip(-+0)
 s = s.lstrip(.)
 s = s.lstrip(0)
 s = s.lstrip(.)
Why the repeated strips? Couldn't this all just be done with
lstrip('-+0.') ?
Yes. Thanks, Kent.
def sigDigits(n):
 
 Strips any real decimal (as string) to just its
significant digits,
 then returns its length, the number of significant
digits. 
 Examples: -345 - 345 -
3;
 3.000 - 3000 - 4
 0.0001234 - 1234 -
4;
 10.0001234 - 11234
- 9
 7.2345e+543 - 72345 -
5
 
 s = n.lstrip('-+0.')
 s = s.replace(., ) 
 if e in s:
 s =
s.rstrip(+-0123456789)
 s =
s.rstrip(e)
 return len(s)

How many significant digits
are in 123000?
Function returns 6, but could be 3, 4, 5, or 6. That's OK for my
purposes. Got a suggestion for these cases?
Dick



UliPad The Python Editor:

http://code.google.com/p/ulipad/


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] setting program configuration for all files and modules of a program

2008-04-14 Thread Tim Michelsen
Hello,
I am building a simple GUI for a calculation program. I am using config 
files (*.cfg) and reading them in with ConfigParser. This works well 
because I have nearly all code in 1 text file.
But I would like to modularize my code and separate the GUI code from 
the functional code that provides the calculation operations. This will 
help to expand the functionality at a later stage. I want to achieve 
this through splitting the code into different modules.
The problem is now that I would always have to write the configration 
file specific code in each module that uses the configration settings 
(see code below).

How can I provide the settings stored in the configuration file 
throughout my program to all functions without needing to initiate the 
ConfigParser object in each module?

I through of having a special module settings.py which I could use to 
read in the configuration from the file and then import this in each module.

Is there a more decent and elegant way?
What is the state of the art in storing and parsing configuraions in 
python programs?

Kind regards,
Timmie



# CODE #
import sys
import locale
import ConfigParser
import gettext


## Path to configuration file
configuration_file_name = './config/program_settings.cfg'# name of 
the configuration file

## read configuration from config file
try:
 program_config = ConfigParser.ConfigParser()
 program_config.readfp(open(configuration_file_name))
except IOError, (errno, strerror):
 error_msg_exception = _(I/O error(%s): %s) % (errno, strerror)
 error_msg_no_config = _(No configuration file with name ), 
configuration_file_name, _(found in the program directory. Please copy 
your configuration there. Values will be replaced by defaults.)
 print error_msg_exception
 print error_msg_no_config
 easygui.msgbox(error_msg_no_config)
 #pass

output = program_config.get('output', 'file_extension')
#

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Conventions for code snippets for debugging and testing?

2008-04-14 Thread Ricardo Aráoz
Robert Kirkpatrick wrote:
 Hi All,
 
 Just wondering if there are any basic conventions for including code
 snippets that are for testing / debugging only?
 
 For example, you could set a boolean variable called DEBUG, then have
 snippets of code like:
 
 if DEBUG:
 do stuff
 else:
 do otherstuff
 
 The use case I'm dealing with right now is to query the SVN commits for a
 weekly period and report on each user for that time period.  If I'm testing
 though, I only want to cycle through a few users, not all of them.
 
 I'm thinking there has to be something slicker than that but maybe not...
 
 Thoughts?
 
 Rob
 

Check the logging standard module. I use it this way (from the manual) :

code

import logging

logging.basicConfig(level=logging.DEBUG,
 format='%(asctime)s %(levelname)s %(message)s',
 filename='/tmp/myapp.log',
 filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')

/code

I put the logging.debug('dbg messg') at the appropriate places. When I'm 
done then I replaces the logging.basicConfig(level=logging.CRITICAL or 
just 100 so as not to log anything and that's it.
You have 6 preset levels, but you can define as many levels you want.

Level   Numeric value
CRITICAL50
ERROR   40
WARNING 30
INFO20
DEBUG   10
NOTSET  0


Once you have your logging set you use a tail program to watch your log 
and see what's going on.

HTH


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] cut all decimal places with zeros

2008-04-14 Thread Tim Michelsen
Hello,
how can I suppress the decimal places for (only those) numbers whos 
decimal places are zero (0)?

Example:

 CODE 
In [1]: m = 2.0

In [2]: n = 2.56789080

In [3]: n_format =  '%.4f' %n

In [4]: n_format
Out[4]: '2.5679'

In [5]: m_format =  '%.4f' %m

In [6]: m_format
Out[6]: '2.'

### END 

I would like to have the m_format to be formatted like 2 and the 
n_format like 2.5679. How can I achive this?
A g with 2.4 should return 2.4 and not 2.4000.

Basically, I am looking for a way to eliminate the decimal places that 
are zero (0).

I tried this humble function before appling the formatting and it works 
well with the numbers:

### CODE ###
def cut_decimals(float):

input: floating number
output: number as string with zero decimals removed

#print float-int(float)
#print '%.4f' %float
if float-int(float) != 0:
number =  '%.4f' %float
number = number.replace('0.','X.')
number = number.replace('0','')
number = number.replace('X.','0.')
else:
number =  '%.0f' %float
return number

n = 2.0
m = 2.5678908
g = 2.4
h = 1.45
i = 0.67
numbers = [n, m, g, h, i]
for i in numbers:
i_f = cut_decimals(i)
print i_f

### END ###
### OUTPUT ###


  %run ./test_number.py
2
2.5679
2.4
1.45
0.67
### END ###

Is there any more efficient solution using string formatting only?

Thanks in adavance.

Kind regards,
Timmie

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-14 Thread Tim Michelsen
 Yes, thats the way I'd recommend.
 Is there a more decent and elegant way?
I don't know. I was just asking how other programmers achive this 
efficiently.


 Another option is to have the config settiongs in a normal
 Python module and just import it. That is less appealing if
 the config file is shared with a non python program, but if
 its all Python then that's a much simpler approach...
I think that the cfg-files are much more readable for others.

 PS.
 Why all the parens around the error strings in your code?
I am using gettext:

_ = gettest.gettest

Got this from the documentation.

Thanks for your reply!

Timmie


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Open url in browser window

2008-04-14 Thread Michael Finlayson
Hi all,

 

This is a serious newbie question. I started this morning. I need to do two
simple things (simple on a PC anyway), and I would like to ask the group if
it is even possible on a Mac before I go through learning Python.

 

I am a partner in an online training company. All training is delivered via
the web. Thus far, our training is accessed via an executable launcher in
Windows. We have been asked to create such a launching interface for a Mac
based client.

 

We use this approach for several reasons. For the security of our training
and the security of our clients computers, we do not allow students to know
where the training is on the web (to prevent unauthorized access), or visit
any other websites. No surfing while training! We do this by opening a
browser window of a specific size with no url line, no menus, nothing except
scroll bars, if necessary.

 

Also, to discourage trainees from skipping out of the training to launch
other applications, we also disable the tab key and control/alt/delete.

 

Are either or both of these possible on a Mac using Python? Again, we need
to:

 

1.   Control the default browser parameters (like you can setup popup
windows in javascript with the onClick=MM_openBrWindow command)

2.   Control of the user’s keyboard.

 

Obviously, these are both temporary and functionality is restored upon
exiting the training.

 

Thank you for your input.

 

Michael Finlayson


No virus found in this outgoing message.
Checked by AVG. 
Version: 7.5.519 / Virus Database: 269.22.13/1376 - Release Date: 4/13/2008
1:45 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cut all decimal places with zeros

2008-04-14 Thread Kent Johnson
Tim Michelsen wrote:
 Hello,
 how can I suppress the decimal places for (only those) numbers whos 
 decimal places are zero (0)?

I don't know how to do this with just string formatting but I think
('%.4f' % n).rstrip('.0')
will do what you want.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules of a program

2008-04-14 Thread Kent Johnson
Tim Michelsen wrote:
 What is the state of the art in storing and parsing configuraions in 
 python programs?

It is pretty common to have a configuration module that is imported 
wherever the configuration is needed. This is simple but it is 
essentially global state and shares some of the disadvantages of 
globals; in particular it couples all your code to the settings module 
and makes testing more difficult.

The alternative is to pass a configuration object to whatever needs it. 
This eliminates the coupling but is more painful to implement.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor