Re: getting local system information with python

2007-03-16 Thread Justin Ezequiel
On Mar 16, 2:27 pm, Astan Chee [EMAIL PROTECTED] wrote:
 Hi,
 I have a python script and I want to check what operating system it is
 on and what the current local machine name is.
 How do I do it with python?
 Thanks!
 Astan

import platform
platform.uname()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Paul Rubin
n00m [EMAIL PROTECTED] writes:
 http://rapidshare.com/files/21267938/m1000.txt
 http://rapidshare.com/files/21268386/m4000.txt

I get 33190970 for the first set and 0 for the second set.

The first set only makes 38853 distinct dictionary entries, I guess
because the numbers are all fairly small so there's a lot of duplication.
The second set makes 8246860 distinct entries.

I got 128.42 sec runtime on the second set, on a 1.2 ghz Pentium M.
That was with the listcomp in the summation, which burned a lot of
extra memory, but I didn't bother writing out a summation loop.

I guess I can see a few other possible micro-optimizations but no
obvious algorithm improvements.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lock problem

2007-03-16 Thread Ritesh Raj Sarraf
Gabriel Genellina wrote:

 En Thu, 15 Mar 2007 18:31:29 -0300, Ritesh Raj Sarraf [EMAIL PROTECTED]
 escribió:
 
 I'm not sure if there's something wrong in the code mentioned above or
 is it
 really a lock problem.
 
 Try to break the code into smaller pieces to see what is wrong. It's too
 long for somebody to try to understand it.
 

The only break I can do is to remove threading, and the it works fine.
I also noticed that when debugging the threads (when the program stops at a
breakpoint in the thread), data is written properly.

This is what made me think if this really is a locking problem.

Ritesh
-- 
Ritesh Raj Sarraf
RESEARCHUT - http://www.researchut.com
Necessity is the mother of invention.
Stealing logic from one person is plagiarism, stealing from many is research.
The great are those who achieve the impossible, the petty are those who
cannot - rrs

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Paul McGuire
On Mar 16, 12:49 am, n00m [EMAIL PROTECTED] wrote:

 for o in range(int(f.readline())):
   row = map(int, f.readline().split())
   q.append(row[0])
   w.append(row[1])
   e.append(row[2])
   r.append(row[3])

Does this help at all in reading in your data?

numlines = f.readline()
rows = [ map(int,f.readline().split()) for _ in range(numlines) ]
q,w,e,r = zip(rows)

-- Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lock problem

2007-03-16 Thread Ritesh Raj Sarraf
Leo Kislov wrote:

 You're changing environmental variable __kabc_ldap that is shared
 between your threads. Environment is not designed for that kind of
 usage, it was designed for settings. Either use an option to set
 output file or just redirect stdout. If the interface of ldapsearch is
 so lame that it requires environmental variable use env to set the
 variable: env __kabc_ldap=/tmp/wrjhdsf ldapsearch ...

The environment variable is set with temp_file_name which gets the name from
tempfile.mkstemp(), which is run in every thread. So I don't think the
environment variable is going to be the same.

Ritesh
-- 
Ritesh Raj Sarraf
RESEARCHUT - http://www.researchut.com
Necessity is the mother of invention.
Stealing logic from one person is plagiarism, stealing from many is research.
The great are those who achieve the impossible, the petty are those who
cannot - rrs

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Paul Rubin wrote:

 n00m [EMAIL PROTECTED] writes:
 h = collections.defaultdict(itertools.repeat(0).next)
 
 Something wrong with 
h = collections.defaultdict(int)
 ?

According to a post by Raymond Hettinger it's faster to use that iterator
instead of `int`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lock problem

2007-03-16 Thread Leo Kislov
On Mar 16, 12:40 am, Ritesh Raj Sarraf [EMAIL PROTECTED] wrote:
 Leo Kislov wrote:
  You're changing environmental variable __kabc_ldap that is shared
  between your threads. Environment is not designed for that kind of
  usage, it was designed for settings. Either use an option to set
  output file or just redirect stdout. If the interface of ldapsearch is
  so lame that it requires environmental variable use env to set the
  variable: env __kabc_ldap=/tmp/wrjhdsf ldapsearch ...

 The environment variable is set with temp_file_name which gets the name from
 tempfile.mkstemp(), which is run in every thread. So I don't think the
 environment variable is going to be the same.

But you miss the fact that there is only one environment per process.

  -- Leo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python shell on mac os x

2007-03-16 Thread martin . laloux
or go to
http://pythonmac.org/packages/
 and you have python 2.5 or python 2.4.4 with readline support

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread Jon Clements
On 16 Mar, 03:56, hiro [EMAIL PROTECTED] wrote:
 Hi there,

 I'm very new to python, the problem I need to solve is whats the best/
 simplest/cleanest way to read in multiple files (ascii), do stuff to
 them, and write them out(ascii).

 --
 import os

 filePath = ('O:/spam/eggs/')
 for file in os.listdir(filePath):   #straight from docs
 # iterate the function through all the files in the directory
 # write results to separate files  - this is where I'm mostly
 stuck.

 --
 For clarity's sake, the file naming conventions for the files I'm
 reading from are file.1.txt - file.nth.txt

 It's been a long day, i'm at my wits end, so I apologize in advance if
 I'm not making much sense here.
 syntax would also be great if you can share some recipes.

I'd try the glob module.

[code]
import glob

# Get a list of filenames matching wildcard criteria
# (note that path is relative to working directory of program)
matching_file_list = glob.glob('O:/spam/eggs/*.txt')

# For each file that matches, open it and process it in some way...
for filename in matching_file_list:
infile = file(filename)
outfile = file(filename + '.out','w')
# Process the input file line by line...
for line in infile:
pass # Do something more useful here, change line and write to
outfile?
# Be explicit with file closures
outfile.close()
infile.close()
[/code]

Of course, you can change the wild card criteria in the glob
statement, and also then filter further using regular expressions to
choose only files matching more specific criteria. This should be
enough to get you started though.

hth

Jon.








-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread Jon Clements
On 16 Mar, 09:02, Jon Clements [EMAIL PROTECTED] wrote:
 On 16 Mar, 03:56, hiro [EMAIL PROTECTED] wrote:





  Hi there,

  I'm very new to python, the problem I need to solve is whats the best/
  simplest/cleanest way to read in multiple files (ascii), do stuff to
  them, and write them out(ascii).

  --
  import os

  filePath = ('O:/spam/eggs/')
  for file in os.listdir(filePath):   #straight from docs
  # iterate the function through all the files in the directory
  # write results to separate files  - this is where I'm mostly
  stuck.

  --
  For clarity's sake, the file naming conventions for the files I'm
  reading from are file.1.txt - file.nth.txt

  It's been a long day, i'm at my wits end, so I apologize in advance if
  I'm not making much sense here.
  syntax would also be great if you can share some recipes.

 I'd try the glob module.

 [code]
 import glob

 # Get a list of filenames matching wildcard criteria
 # (note that path is relative to working directory of program)
 matching_file_list = glob.glob('O:/spam/eggs/*.txt')

 # For each file that matches, open it and process it in some way...
 for filename in matching_file_list:
 infile = file(filename)
 outfile = file(filename + '.out','w')
 # Process the input file line by line...
 for line in infile:
 pass # Do something more useful here, change line and write to
 outfile?
 # Be explicit with file closures
 outfile.close()
 infile.close()
 [/code]

 Of course, you can change the wild card criteria in the glob
 statement, and also then filter further using regular expressions to
 choose only files matching more specific criteria. This should be
 enough to get you started though.

 hth

 Jon.- Hide quoted text -

 - Show quoted text -

Okies; postcoding before finishing your early morning coffee is not
the greatest of ideas!

I forgot to mention that glob will return pathnames as well. You'll
need to check that os.path.isfile(filename) returns True before
processing it...

Jon.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distributing python software in jar like fashion

2007-03-16 Thread Gary Duzan
In article [EMAIL PROTECTED], alf  [EMAIL PROTECTED] wrote:
Hi,

I have a small app which consist of a few .py files. Is there any way to 
distribute it in jar like fashion as a single file I can just run python 
on. I obviously look for platform independent solution.

Thx in advance, A.

   There is a new package that has been discussed here recently
called Squisher that should do what you want by packing things into
a single pyc file. There are still some minor issues that need to
be ironed out with running the pyc directly, but it should do
exactly what you want Real Soon Now.

http://groups.google.com/groups/search?q=group%3Acomp.lang.python+squisherqt_s=Search

Gary Duzan
Motorola CHS


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execfile locks file forever if there are any syntax errors - is it python bug?

2007-03-16 Thread Slawomir Nowaczyk
On Wed, 14 Mar 2007 07:59:57 -0500
[EMAIL PROTECTED] wrote:

# 
# Slawomir When I execfile a file which contains a syntax error, the file
# Slawomir becomes locked and stays this way all the way until I exit the
# Slawomir interpreter (I am unable to delete it, for example). I have
# Slawomir tried but failed to find any way to unlock the file... Is this
# Slawomir a bug in Python?
# 
# Kinda seems like it might be.  Please file a bug report on SourceForge.

I did, and it is a bug, but it seems to be already fixed in SVN.

https://sourceforge.net/tracker/?func=detailatid=105470aid=1681020group_id=5470

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

Does a clean house indicate that there is a broken computer in it?

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Readline()

2007-03-16 Thread Taylor, Stuart
for anyone who gets this same problem i managed to resolve the issue
using two threads.
The main program spawned a subprocess and used readlines to read the
output. The process spawned was a script which executes a command using
a thread. The thread reads the output from this command using readline.
Within the main loop of the script there is a while loop which checks
when the last output from the command was and if the time elapsed is
greater than timeout the script prints to the stdout a string called
timeout.
In the main program the readline compares every output to see if it
matches this sting. if it does kill process :)
 
I'm sure this code could be implemented better but it works and got me
out of a hole
 
heres the thread script which contains the thread class and the time out
loop:
 
import datetime
import time
import threading
import subprocess
import os
import sys
class outputThread(threading.Thread):

Thread is used to print the output of a command to the stdout

def __init__(self,threadCommand, name=thread, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.name   = name
self.killed = 0
self.counter= 0
self.command= threadCommand
self.retval = None
self.Set_Hit()
def run(self):
self.Proc   = subprocess.Popen(self.command, cwd =
os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr =
subprocess.STDOUT)
self.retval = None
self.Set_Hit()
while self.retval == None and not self.killed:   
line = self.Proc.stdout.readline()
print line.rstrip(\r\n)
sys.stdout.flush()
self.Set_Hit()
self.retval=self.Proc.poll()
def Set_Hit(self):
self.last_time = datetime.datetime.now()  
def Get_Hit(self):
return self.last_time

if __name__ == __main__:

This script is designed to put a timeout loop over a thread.
The intention of this thread is to perform a command and have a
timer loop over
checking for the last text ouput from the command.
If the loop exceeds the set time limit the command will stop reading
the output from the thread

command = []
timeout = 5
maxCounter  = timeout
curCounter  = 0
strCounter  = 0
if len(sys.argv)  2:
try:
timeout   = int(sys.argv[1])
except:
print time out value is not a float
sys.exit(1)
for argPos in range(2,len(sys.argv)):
print arg = %s % sys.argv[argPos]
command.append(sys.argv[argPos])
else:
print not enough arguments
sys.exit(1)
thread1 = outputThread(command,name=thread1)
thread1.start()
while True:
if not thread1.retval == None:
sys.exit(0)
#Get current time and when timeout should occur
currentTime = datetime.datetime.now()
elapsedTime = thread1.Get_Hit() +
datetime.timedelta(minutes=timeout)
#Check Elapsed time
if elapsedTime  currentTime:
print timed out
sys.stdout.flush()
break
time.sleep(1)



From: Taylor, Stuart [mailto:[EMAIL PROTECTED] 
Sent: 13 March 2007 09:50
To: Sick Monkey; Taylor, Stuart
Cc: python-list@python.org
Subject: RE: Readline()


i have a thread class which should read the output from the procedure
line by line and finish when the thread is set to kill:
 
class KillableThread(threading.Thread):
def __init__(self, name=thread, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.name = name
self.killed = 0
def kill(self):
self.killed = 1
def run(self):
self.id = threading._get_ident()
self.Proc  =
subprocess.Popen([python,-tt,output_file.py], cwd =
os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr =
subprocess.STDOUT)
retval= None 
while retval == None and not self.killed:
line = self.Proc.stdout.readline()
retval=self.Proc.poll()
 
to replicate my problem the output_file.py requires a user input. i ask
for a user input as my thread will sit waiting on
self.Proc.stdout.readline(). This is the point i want to have a timeout
or be able to end my thread as there is no output from the output_file. 
 
The main approch i cannot implement is to be able to kill the thread as
it remains hung on readlines()
 



From: Sick Monkey [mailto:[EMAIL PROTECTED] 
Sent: 13 March 2007 01:51
To: Taylor, Stuart
Cc: python-list@python.org
Subject: Re: Readline()


Maybe if you show us your code we can better assist you.  

But maybe you can use a global variable or a try-catch method to keep
threads from staying alive and help better control your code.  


On 3/12/07, Taylor, Stuart 

CSV module and fileobj

2007-03-16 Thread Jon Clements
Hi Group,

If I have a CSV reader that's passed to a function, is it possible for
that function to retrieve a reference to the fileobj like object
that was passed to the reader's __init__? For instance, if it's using
an actual file object, then depending on the current row, I'd like to
open the file object again, seek to the current position, then create
a csv.reader on that, exhaust it until a certain point, then return.
ie, leaving the passed iterator intact and ready to carry on as
normal.

(And yes, I know passing in the source object is probably easier --
assume a constraint that I can't...)

Cheers,

Jon.

-- 
http://mail.python.org/mailman/listinfo/python-list


Writing python module in C: wchar_t or Py_UNICODE?

2007-03-16 Thread Yury
I am new to python and programming generally, but someday it is time
to start :)
I am writing a python module in C and have a question about multibyte
character strings in python=C.
I want a C function which takes a string as argument from python
script:

static PyObject *
connect_to_server(PyObject *self, PyObject * authinfo){
wchar_t * login;  /* Must support unicode */
char * serveraddr;
int * port;

if(!PyArgsParseTuple(authinfo, sdu, serveraddr, port, login))
return NULL;

...

Will that code work?
Or i should use Py_UNICODE * data type? Will it be compatible with
standard C string comparison/concantenation functions?

-- 
http://mail.python.org/mailman/listinfo/python-list


Sharing Objects in Python

2007-03-16 Thread Clement
Can a object sharable by two different python programs... If so can you please 
explain... because my project needs two programs to access nearly 45GB file 
Symentaniously...


By
  Clement Jeba kumar,
  Tenkasi.

 
-
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.-- 
http://mail.python.org/mailman/listinfo/python-list

Mastering Python

2007-03-16 Thread Gerald
Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
curriculum did not include Python programming yet I see many vacancies
for Python developers.I studied programming Pascal,C++ and Delphi.So I
need to catch up quickly and master Python programming.How do you
suggest that I achieve this goal?Is python platform independent?What
is the best way?And how long would it take before I can develop
applications using python?Can you recommend websites that feature a
gentle introduction to Python?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using wildcards with Popen in the Subprocess module

2007-03-16 Thread Sion Arrowsmith
William Hudspeth  [EMAIL PROTECTED] wrote:
 [ ... ] I need to pass multiple filenames to an
executable. The filenames are similar to one another, but differ only
slightly, hence the use of the wildcard. The executable works well from
the command line if I pass in a wildcard filename, but Popen can't
expand the wildcard.

From command line:
% command /path_to_files/filename*.doc

With Popen:
var1=/path_to_files/filnames*.doc
result=Popen([command,var1]).wait()

You want:

result = Popen([command, var1], shell=True).wait()

See the subprocess docs on using Popen instead of older functions
(especially os.system): http://docs.python.org/lib/node534.html .
You might also want a look at subprocess.call() .

-- 
\S -- [EMAIL PROTECTED] -- 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: problem with str()

2007-03-16 Thread Steve Holden
Alex Martelli wrote:
 Steve Holden [EMAIL PROTECTED] wrote:
...
 Get yourself a stuffed bear, and next time you have this kind of problem
 spend a few minutes explaining to the bear exactly how your program
 can't possibly be wrong. Works like a charm.
 A rubber ducky works much better for that, btw -- more easily washable
 than a stuffed bear, for example.

 But stuffed bears are so much more knowledgeable about the minutiae of
 software design.
 
 And yet, the key to Python's strength is duck typing -- if you can teach
 the duck to type, you've got it made.
 
 
That's bearly a joke at all :)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Registration Open for South Florida Software Symposium 2007

2007-03-16 Thread K
It is just a good news.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread Laurent Rahuel
Maybe the walk method in os module is what you need
http://docs.python.org/lib/os-file-dir.html

Regards

Jon Clements wrote:

 On 16 Mar, 09:02, Jon Clements [EMAIL PROTECTED] wrote:
 On 16 Mar, 03:56, hiro [EMAIL PROTECTED] wrote:





  Hi there,

  I'm very new to python, the problem I need to solve is whats the best/
  simplest/cleanest way to read in multiple files (ascii), do stuff to
  them, and write them out(ascii).

  --
  import os

  filePath = ('O:/spam/eggs/')
  for file in os.listdir(filePath):   #straight from docs
  # iterate the function through all the files in the directory
  # write results to separate files  - this is where I'm mostly
  stuck.

  --
  For clarity's sake, the file naming conventions for the files I'm
  reading from are file.1.txt - file.nth.txt

  It's been a long day, i'm at my wits end, so I apologize in advance if
  I'm not making much sense here.
  syntax would also be great if you can share some recipes.

 I'd try the glob module.

 [code]
 import glob

 # Get a list of filenames matching wildcard criteria
 # (note that path is relative to working directory of program)
 matching_file_list = glob.glob('O:/spam/eggs/*.txt')

 # For each file that matches, open it and process it in some way...
 for filename in matching_file_list:
 infile = file(filename)
 outfile = file(filename + '.out','w')
 # Process the input file line by line...
 for line in infile:
 pass # Do something more useful here, change line and write to
 outfile?
 # Be explicit with file closures
 outfile.close()
 infile.close()
 [/code]

 Of course, you can change the wild card criteria in the glob
 statement, and also then filter further using regular expressions to
 choose only files matching more specific criteria. This should be
 enough to get you started though.

 hth

 Jon.- Hide quoted text -

 - Show quoted text -
 
 Okies; postcoding before finishing your early morning coffee is not
 the greatest of ideas!
 
 I forgot to mention that glob will return pathnames as well. You'll
 need to check that os.path.isfile(filename) returns True before
 processing it...
 
 Jon.

-- 
http://mail.python.org/mailman/listinfo/python-list


getopt or optparse options/arguments wrapping?

2007-03-16 Thread Rocky Zhou
I wonder is there any way to make the wrapper program can wrap options
 arguments for the  the  subprocess/command the wrapper will
execute? by getopt or optparse module?

This is something like the shell script like this:
optwrap=
while [ $# -gt 0 ]; do
   case $1 in
   -a) do-something; shift
   ;;
   -b) do-something; shift
   ;;
   *)  optwrap=$optwrap $1 $2
  # collect the option and argument
   shift
   ;;
   esac
   shift
done

$command $optwrap
# execute the command with $optwrap as subprocess

I want that all the options and arguments which are feed to this
scripts command line will be used by executing the sub command.

I need this because I now have finished a fs_backup script written in
python, it will execute tar  find to complete full and
differentiating/incremental backup for the file system level files,
and their restoring. This script will do different things by the
command line arguments, and execute find/tar in different ways, but
for being more flexible, I want some options of tar/find can also been
specified from the command line directly, and the script just transmit
those to tar/find simply.

Is there anyone can give me some advices?

Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Eggs on Cygwin

2007-03-16 Thread Jason Tishler
Kazu,

On Thu, Mar 15, 2007 at 05:33:29PM -0700, Kazu Nisimura wrote:
  import MySQLdb
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File build/bdist.cygwin-1.5.22-i686/egg/MySQLdb/__init__.py, line
 19, in ?
   File build/bdist.cygwin-1.5.22-i686/egg/_mysql.py, line 7, in ?
   File build/bdist.cygwin-1.5.22-i686/egg/_mysql.py, line 6, in
 __bootstrap__
 ImportError: Permission denied
 
 This seems to be Eggs/Cygwin problem.  Is there any solution?

The following is a WAG...

Does the MySQL Python module contain shared extension modules (i.e.,
DLLs)?  If so, are they executable?  If not, then make them so (i.e.,
chmod +x).

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread Jordan
On Mar 16, 7:09 am, Laurent Rahuel [EMAIL PROTECTED] wrote:
 Maybe the walk method in os module is what you 
 needhttp://docs.python.org/lib/os-file-dir.html

 Regards

 Jon Clements wrote:
  On 16 Mar, 09:02, Jon Clements [EMAIL PROTECTED] wrote:
  On 16 Mar, 03:56, hiro [EMAIL PROTECTED] wrote:

   Hi there,

   I'm very new to python, the problem I need to solve is whats the best/
   simplest/cleanest way to read in multiple files (ascii), do stuff to
   them, and write them out(ascii).

   --
   import os

   filePath = ('O:/spam/eggs/')
   for file in os.listdir(filePath):   #straight from docs
   # iterate the function through all the files in the directory
   # write results to separate files  - this is where I'm mostly
   stuck.

   --
   For clarity's sake, the file naming conventions for the files I'm
   reading from are file.1.txt - file.nth.txt

   It's been a long day, i'm at my wits end, so I apologize in advance if
   I'm not making much sense here.
   syntax would also be great if you can share some recipes.

  I'd try the glob module.

  [code]
  import glob

  # Get a list of filenames matching wildcard criteria
  # (note that path is relative to working directory of program)
  matching_file_list = glob.glob('O:/spam/eggs/*.txt')

  # For each file that matches, open it and process it in some way...
  for filename in matching_file_list:
  infile = file(filename)
  outfile = file(filename + '.out','w')
  # Process the input file line by line...
  for line in infile:
  pass # Do something more useful here, change line and write to
  outfile?
  # Be explicit with file closures
  outfile.close()
  infile.close()
  [/code]

  Of course, you can change the wild card criteria in the glob
  statement, and also then filter further using regular expressions to
  choose only files matching more specific criteria. This should be
  enough to get you started though.

  hth

  Jon.- Hide quoted text -

  - Show quoted text -

  Okies; postcoding before finishing your early morning coffee is not
  the greatest of ideas!

  I forgot to mention that glob will return pathnames as well. You'll
  need to check that os.path.isfile(filename) returns True before
  processing it...

  Jon.

Also, leaving the format as .out is not necessarily convenient.  You
had glob do a search for .txt, so how about doing:

Also, Python advises using open() over file() (although I admit to
using file() myself more often than not)
for filename in matching_file_list:
 infile = open(filename,'r') # add 'r' for clarity if nothing else
 outfile = open(filename[:-4] + '.out.txt','w') # assumes file ext of 
 original file is .txt
 # Process the input file line by line...
 for line in infile:
 pass # do thing -- you don't have to iterate line by line, if you 
 specified what you wanted to do to each file we could probably help out here 
 if you need it.
 # Be explicit with file closures
 outfile.close()
 infile.close()

Might also add some try/except statements to be safe ;).

Cheers,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV module and fileobj

2007-03-16 Thread skip

Jon If I have a CSV reader that's passed to a function, is it possible
Jon for that function to retrieve a reference to the fileobj like
Jon object that was passed to the reader's __init__? 

Nope, that isn't exposed from the C type.

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Hello alltogether,

is it possible to format stings with fixed width of let's say 7 character. T 
need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
after 
dot, padded with '0'.

Followingh is my approach
  f = 21.1
  s = %.03f % f
  s
'21.100'

But there are missing ' '. How can I get that? (For bigger numbers than 999 
they 
might be cut: 1021 - 021)

Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Hello alltogether,

is it possible to format stings with fixed width of let's say 7 character. T 
need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
after 
dot, padded with '0'.

Followingh is my approach
  f = 21.1
  s = %.03f % f
  s
'21.100'

But there are missing ' '. How can I get that? (For bigger numbers than 999 
they 
might be cut: 1021 - 021)

Thanks,
Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Gerald wrote:

 Can you recommend websites that feature a gentle introduction to Python?

If you already know programming in general, `Dive Into Python`_ might be a
good starting point.  And of course the tutorial in the Python
documentation.

_Dive Into Python: http://www.diveintopython.org/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Anton Vredegoor
n00m wrote:

 62.5030784639

Maybe this one could save a few seconds, it works best when there are 
multiple occurrences of the same value.

A.

from time import time

def freq(L):
  D = {}
  for x in L:
  D[x] = D.get(x,0)+1
  return D

def test():
 t = time()
 f = file('m4000.txt')
 f.readline()
 L = []
 for line in f:
 L.append(map(int,line.split()))

 q,w,e,r = map(freq,zip(*L))
 sch,h = 0,{}
 for xk,xv in q.iteritems():
   for yk,yv in w.iteritems():
 if h.has_key(xk+yk):
   h[xk+yk] += xv*yv
 else:
   h[xk+yk] = xv*yv

 for xk,xv in e.iteritems():
   for yk,yv in r.iteritems():
 if h.has_key(-(xk+yk)):
   sch += h[-(xk+yk)]*xv*yv

 print sch
 print time()-t

if __name__=='__main__':
 test()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Bruno Desthuilliers
Gerald a écrit :
 Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
 curriculum did not include Python programming yet I see many vacancies
 for Python developers.I studied programming Pascal,C++ and Delphi.So I
 need to catch up quickly and master Python programming.How do you
 suggest that I achieve this goal?Is python platform independent?What
 is the best way?And how long would it take before I can develop
 applications using python?Can you recommend websites that feature a
 gentle introduction to Python?

Most of your questions are answered on python.org. May I suggest that 
you start there ?

Briefly:
  * mastering a language takes years, whatever the language.
  * the first step is of course learning the language !-)
  * given your background, I'd suggest first the official Python 
tutorial, then diveintopython. Reading this ng might help too.
  * Yes, Python is (mostly) platform-independent - at least as long a 
you don't use platform-dependent modules
  * An average programmer may become productive with Python in a matter 
of days - but really taking advantage of Python's power is another story.


If you like programming, chances are you'll enjoy Python. So welcome on 
board !-)

HTH


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Steve Holden
Alexander Eisenhuth wrote:
 Hello alltogether,
 
 is it possible to format stings with fixed width of let's say 7 character. T 
 need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
 after 
 dot, padded with '0'.
 
 Followingh is my approach
   f = 21.1
   s = %.03f % f
   s
 '21.100'
 
 But there are missing ' '. How can I get that? (For bigger numbers than 999 
 they 
 might be cut: 1021 - 021)
 
   def f(x):
  ...   return %7.3f % (x % 1000.0)
  ...
   for x in (9.9, 99.9, 999.9, .9):
  ...   print f(x)
  ...
   9.900
  99.900
999.900
999.900
  

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Importing

2007-03-16 Thread HMS Surprise

Greetings,

First I will admit I am new to Python but have experience with C++ and
some Tcl/Tk. I am starting to use a tool called MaxQ that  uses
jython. I have been studying Rossum's tutorial but still am unclear on
importing, the use of self, and calling functions with their own name
in quotes. In the code below the lines between #Start and #End are
generated by browsing web pages. In a large test this section can
become quite large. The maxQ documentation suggests breaking it up
into functions. If so could these functions be placed in a separate
file and imported? Is it acceptable to import into a class? If
imported as a function will self as used here need to be changed?
Would it be better to duplicate class and import whole classes?

Any suggestions will be appreciated, especially other Python
tutorials.

Best Regards,

jh

~

# Generated by MaxQ
[com.bitmechanic.maxq.generator.JythonCodeGenerator]
from PyHttpTestCase import PyHttpTestCase
from com.bitmechanic.maxq import Config
global validatorPkg
if __name__ == 'main':
validatorPkg = Config.getValidatorPkgName()
# Determine the validator for this testcase.
exec 'from '+validatorPkg+' import Validator'


# definition of test class
class MaxQTest(PyHttpTestCase):
def runTest(self):
self.msg('Test started')

#Start

self.msg(Testing URL: %s % self.replaceURL('''http://
www.dogpile.com/'''))
url = http://www.dogpile.com/;
params = None
Validator.validateRequest(self, self.getMethod(), get, url,
params)
self.get(url, params)
self.msg(Testing URL: %s % self.replaceURL('''http://
www.dogpile.com/favicon.ico'''))
url = http://www.dogpile.com/favicon.ico;
params = None
Validator.validateRequest(self, self.getMethod(), get, url,
params)
self.get(url, params)

#End

# ^^^ Insert new recordings here.  (Do not remove this line.)


# Code to load and run the test
if __name__ == 'main':
test = MaxQTest(MaxQTest)


#   test.Run()  #Either of these two lines work equally well.
test.runTest()  #I suspect that Run() is a method of
PPyHttpTestCase or a builtIn

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Jon Clements
On 16 Mar, 13:20, Alexander Eisenhuth [EMAIL PROTECTED]
wrote:
 Hello alltogether,

 is it possible to format stings with fixed width of let's say 7 character. T
 need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
 after
 dot, padded with '0'.

 Followingh is my approach
   f = 21.1
   s = %.03f % f
   s
 '21.100'

 But there are missing ' '. How can I get that? (For bigger numbers than 999 
 they
 might be cut: 1021 - 021)

You can use something like this:
 print '%7.03f' % 21.1
' 21.100'


However, this will only make the string at *least* 7 long. If the
length of the number exceeds this, you'll end up with it even longer;
for instance:

 print '%7.03f' % 2123123121.1
'2123123121.100'

From your example about 'cutting' it, it looks like you just might be
able to take the last 7 chars from it using [-7:]

hth

Jon.






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV module and fileobj

2007-03-16 Thread Bruno Desthuilliers
Jon Clements a écrit :
 Hi Group,
 
 If I have a CSV reader that's passed to a function, is it possible for
 that function to retrieve a reference to the fileobj like object
 that was passed to the reader's __init__? For instance, if it's using
 an actual file object, then depending on the current row, I'd like to
 open the file object again, seek to the current position, then create
 a csv.reader on that, exhaust it until a certain point, then return.
 ie, leaving the passed iterator intact and ready to carry on as
 normal.
 
 (And yes, I know passing in the source object is probably easier --
 assume a constraint that I can't...)
 

As Skip pointed out, this won't work that way. There might be a possible 
workaround using itertools.tee and eventually StringIO.

My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Paul McGuire
On Mar 16, 6:41 am, Gerald [EMAIL PROTECTED] wrote:
 Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
 curriculum did not include Python programming yet I see many vacancies
 for Python developers.I studied programming Pascal,C++ and Delphi.So I
 need to catch up quickly and master Python programming.How do you
 suggest that I achieve this goal?Is python platform independent?What
 is the best way?And how long would it take before I can develop
 applications using python?Can you recommend websites that feature a
 gentle introduction to Python?

Stop thinking about *how* to start and *just start*.  Python is pretty
intuitive, especially if you have other language background to relate
to.  Download the Python dist for your platform (Linux? probably
already there - Windows? binary installers from python.org or
activestate will install in a snap).  Run through the first few pages
of any of the dozen or more online tutorials to start getting your
fingernails dirty.  You'll need a text editor with integrated building
- I find SciTE and PyScripter to be good for beginners (and I still
use SciTE after 4 years of Python programming).

You know C++ and Pascal?  You already know the basic if-then-else,
while, and for control structure concepts.  Here are some C++-to-
Python tips:
- There's no switch statement in Python.  Make do with cascading if/
elif/else until you come across the dict dispatch idiom.
- There's no '?' operator in Python.  If you download the latest
version (2.5), there is an equivalent x if y else z which would map
to y ? x : z using the ternary operator.  But lean towards explict
readability vs. one-liner obscurity at least for a few days.
- Forget about new/delete.  To construct an object of type A, call A's
constructor using newA = A().  To delete A, let if fall out of
scope, or explicitly unbind the object from the name newA with newA
= None.
- Forget about for(x = 0; x  10; x++).  Python loops iterate over
collections, or anything with an __iter__ method or __getitem__
method.  This is much more like C++'s for(listiter = mylist.first();
listiter != mylist.end(); ++listiter).  To force a for loop to
iterate 'n' times, use for i in range(n):.  The range built-in
returns the sequence [0, 1, 2, ..., n-1]. Don't commit this beginner's
blunder:
  list1 = [ 1, 2, 3 ]
  for i in range(len(list1)):
  # do something with list1[i]
Instead do:
  for elem in list1:
  # do something with elem, which points to each element of
  # list1 each time through the loop
If you really need the list index, use enumerate, as in:
  for i,elem in enumerate(list1):
  print The %d item of the list is %s % (i,elem)
(Hey, check out those string formatting placeholders, they borrow
heavily from C's printf notation.  Oh, they don't teach that anymore,
and you used iostreams in C++ instead?  Bummer.)
- Forget about braces {}'s.  For some reason, this is a big deal for
some people, but give it a chance.  Just indent code as you would
normally, and leave out the braces.  Personally I set my editor to
replace tabs with spaces, this is a style choice - but do NOT mix tabs
and spaces.  In the end, you will find this liberating, especially if
you have ever been on a project that had to define a coding standard,
and spent way too much time (more then 30 seconds) arguing about
where the braces should go.
- Don't forget the ()'s.  To invoke a method on an object, you must
include the parens.  This wont do anything:
  a = some string
  a = a.lower
You need this:
  a = a.lower()
- Stop thinking about variables as addresses and storage locations,
and start thinking about them as values bound to names.  Even so, I
still find myself using words like assignment and variable, when
strictly I should be saying binding and name.

What does Python have that C++ doesn't?
- The biggie: dynamic typing (sometimes called duck typing).
Dynamic typing is a huge simplifier for development:
  . no variable declarations
  . no method type signatures
  . no interface definitions needed
  . no templating for collections
  . no method overloading by differing argument type signatures
(Imagine there's no data types - I wonder if you can...).  What? No
static type-checking at compile time?  Nope, not really.  If your
method expects an object of type X, use it like an X.  If it's not an
X, you may be surprised how often this is not a problem.  For
instance, here's a simple debugging routine:
def printClassOf(x):
print x.__class__.__name__
Every object has the attribute __class__ and every class has the
attribute __name__.  In C++, I'd have to go through extra contortions
*not* to type the variable x, probably call it something non-intuitive
like void*.  Or look at this example:
def printLengthOf(x):
print Length of x is, len(x)
x could be any collection class, or user-defined class that is
sufficiently like a collection to support len (such as implementing
the __len__ method).  This class doesn't even have to exist when you

Re: Mastering Python

2007-03-16 Thread Paul McGuire
On Mar 16, 6:41 am, Gerald [EMAIL PROTECTED] wrote:
 Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
 curriculum did not include Python programming yet I see many vacancies
 for Python developers.I studied programming Pascal,C++ and Delphi.So I
 need to catch up quickly and master Python programming.How do you
 suggest that I achieve this goal?Is python platform independent?What
 is the best way?And how long would it take before I can develop
 applications using python?Can you recommend websites that feature a
 gentle introduction to Python?

P.S. You'll get further faster with Python than with Java or Perl,
where you posted similar how do I master language X? requests.  I've
used Java and suffered through Perl.  Compared to Perl, Python a) has
less magic symbology/punctuation, and b) treats you more like an adult
(open x or die? Come on!).  Java syntax is so bloated you have to
tack on Eclipse plug-ins by the fistful to auto-generate the wrapper
junk code around the code you really wanted to get run.

Get thee to www.python.org, and get going, post haste!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eureka moments in Python

2007-03-16 Thread Paul McGuire
On Mar 13, 2:16 am, Steven D'Aprano [EMAIL PROTECTED]
wrote:
 I'd be interested in hearing people's stories of Eureka moments in Python,
 moments where you suddenly realise that some task which seemed like it
 would be hard work was easy with Python.


The day I wrote a CORBA method intercepter in 8 lines of code using
__getattr__ to catch 2 or 3 interesting method calls out of 20 or 30
defined in the IDL.  The interesting methods I handled, and the rest I
just forwarded to the remote CORBA object.  Unfortunately, the client
expected this to be an expensive job, and I was only able to bill him
for 1/2 an hour (I had to test the code in addition to writing it).

-- Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Steve Holden
Steve Holden wrote:
 Alexander Eisenhuth wrote:
 Hello alltogether,

 is it possible to format stings with fixed width of let's say 7 character. T 
 need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
 after 
 dot, padded with '0'.

 Followingh is my approach
   f = 21.1
   s = %.03f % f
   s
 '21.100'

 But there are missing ' '. How can I get that? (For bigger numbers than 999 
 they 
 might be cut: 1021 - 021)

def f(x):
   ...   return %7.3f % (x % 1000.0)
   ...
for x in (9.9, 99.9, 999.9, .9):
   ...   print f(x)
   ...
9.900
   99.900
 999.900
 999.900
   
 
... but (unfortunately?):

   f(-.99)
'  0.010'
  

You don't say what you want to do about negative numbers, so this may or 
may not be significant.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing python module in C: wchar_t or Py_UNICODE?

2007-03-16 Thread Carsten Haese
On Fri, 2007-03-16 at 04:04 -0700, Yury wrote:
 I am new to python and programming generally, but someday it is time
 to start :)
 I am writing a python module in C and have a question about multibyte
 character strings in python=C.
 I want a C function which takes a string as argument from python
 script:
 
 static PyObject *
 connect_to_server(PyObject *self, PyObject * authinfo){
 wchar_t * login;  /* Must support unicode */
 char * serveraddr;
 int * port;
 
 if(!PyArgsParseTuple(authinfo, sdu, serveraddr, port, login))
 return NULL;
 
 ...
 
 Will that code work?
 Or i should use Py_UNICODE * data type? Will it be compatible with
 standard C string comparison/concantenation functions?

You should familiarize yourself with the Python/C API documentation. It
contains the answers to all the above questions.

http://docs.python.org/api/arg-parsing.html says this about the u
format character: a pointer to the existing Unicode data is stored into
the Py_UNICODE pointer variable whose address you pass.

http://docs.python.org/api/unicodeObjects.html says this about
Py_UNICODE: On platforms where wchar_t is available and compatible with
the chosen Python Unicode build variant, Py_UNICODE is a typedef alias
for wchar_t to enhance native platform compatibility.

The first quote says that, to be strictly correct, login should be a
Py_UNICODE*, but the second quote says that under the right
circumstances, Py_UNICODE is the same as wchar_t. It's up to you to
determine if your platform provides the right circumstances for this to
be the case.

Hope this helps,

Carsten.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Thanks for your fast reply. I'm fine with your %7.03f solution. (negatives 
are 
  not significant)

Alexander Eisenhuth schrieb:
 Hello alltogether,
 
 is it possible to format stings with fixed width of let's say 7 
 character. T need a floating point with 3 chars before dot, padded with 
 ' ' and 3 chars after dot, padded with '0'.
 
 Followingh is my approach
   f = 21.1
   s = %.03f % f
   s
 '21.100'
 
 But there are missing ' '. How can I get that? (For bigger numbers than 
 999 they might be cut: 1021 - 021)
 
 Thanks,
 Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Dave Hansen
On Mar 16, 8:39 am, Paul McGuire [EMAIL PROTECTED] wrote:
[...]
 Stop thinking about *how* to start and *just start*.  Python is pretty

Indeed.  Of all the fortune cookies I've eaten over the years, I've
saved (and taped to my monitor) only one fortune.  It reads:

  Begin...the rest is easy.

Regards,
   -=Dave

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread BartlebyScrivener
On Mar 16, 8:39 am, Paul McGuire [EMAIL PROTECTED] wrote:

 Wow, are you still reading?  Quit wasting time and go download a
 Python dist and get started already!


I think you should extract that and spend twenty minutes tidying it up
and then publish it to the Python for Programmers page or make it a
downloadable .pdf.

http://wiki.python.org/moin/BeginnersGuide/Programmers

rd

 The chief contribution of Protestantism to human thought is its
  massive proof that God is a bore.

  --H.L. Mencken

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing

2007-03-16 Thread Bruno Desthuilliers
HMS Surprise a écrit :
 Greetings,
 
 First I will admit I am new to Python but have experience with C++ and
 some Tcl/Tk. I am starting to use a tool called MaxQ that  uses
 jython. I have been studying Rossum's tutorial but still am unclear on
 importing, 

What's your problem here ?

 the use of self,

In Python, a method is a wrapper around a function. This wrappers as a 
reference to the instance on which the method is called, and calls the 
wrapped function passing the instance as first argument. By convention, 
it's named 'self', but technically you could use any other name. So, to 
make a long story short:
  - you need to declare 'self' as the first argument of a method
  - you need to use self to access the current instance within the 
method body
  - you *don't* have to pass the instance when calling the method

 and calling functions with their own name

You mean the
   test = MaxQTest(MaxQTest)
line ?

First point: it's not a function call, it's an object instanciation. 
There's no 'new' keyword in Python, classes are callable objects acting 
as factory for their instances.

Second point: passing the name of the class here is specific to MaxQ, 
and I'd say it's only used for internal and display stuff.

 in quotes. In the code below the lines between #Start and #End are
 generated by browsing web pages. In a large test this section can
 become quite large. The maxQ documentation suggests breaking it up
 into functions. If so could these functions be placed in a separate
 file and imported?

Yes, but you'd have to bind them to the class manually (cf below).

 Is it acceptable to import into a class?

Yes, but this wont solve your problem. Import creates a module object in 
the current namespace, that's all.

 If
 imported as a function will self as used here need to be changed?

Nope.

def quux(self, foo):
   self.bar += foo

class Boo(object):
   def __init__(self, bar):
 self.bar = bar

Boo.quux = quux
b = Boo(40)
b.quux(2)
print b.bar

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread paul
Paul McGuire schrieb:
 What does Python have that C++ doesn't?
 - The biggie: dynamic typing (sometimes called duck typing).
 Dynamic typing is a huge simplifier for development:
   . no variable declarations
   . no method type signatures
   . no interface definitions needed
   . no templating for collections
   . no method overloading by differing argument type signatures
 (Imagine there's no data types - I wonder if you can...).  What? No
 static type-checking at compile time?  Nope, not really.  If your
 method expects an object of type X, use it like an X.  If it's not an
 X, you may be surprised how often this is not a problem.
But sometimes it is ;) Typical example: input and CGI/whatever. If one
element is checked you'll get a string, if you select multiple (i.e.
checkboxes) you'll get a list. Both support iteration

Now if you iterate over the result:

case 1, input - value1:
for elem in input:
  #in real life we might validate here...
  print elem

- 'v' 'a' 'l' 'u' 'e' '1'

case 2, input - [value1, value2]
for elem in input:
  print elem

- value1 value2

cheers
 Paul

Disclaimer: I like python and I write tests but i wish unittest had
class/module level setUp()...






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python COM called from VB/Delphi

2007-03-16 Thread Jorge Mazzonelli

Larry,

It's been a while since I coded something in VB or Delphi because I'm mostly
turn on Python ;)
so please excuse me any mistakes I can make  8I don't have neither VB or
Delphi installed on this computer)

For Delphi to use an OLE/COM Object it requires a TypeLibrary that explains
how to access to this COM Object. For this you can use Project--Import
TypeLibrary. This will create automatically a .pas file with all the
declaratons needed so you can use the object from Delphi.
The Object exposed from python is from the point of view of Delphi simply a
COM object. So if you need help on implementing a COM client in Delphi I
suggest you to turn to the Delphi-related groups or do some google search
about it.
I found myself a simple tip about optional parameters and how they are
handle in Delphi, here:
http://blogs.teamb.com/CraigStuntz/archive/2005/07/01/UsingCOMOptionalParamsFromDelphi.aspx

On the VB side, you can see on the link below how to create a callback in VB
(it requires calling to the Windows API)
http://www.thevbzone.com/secrets.htm#AddressOf

But if I understand you well, you need to make the client aware that
something has change (the progress of download for example or the end of the
downloading) I think that the simplest way may be to raise events from you
python code. This way the events are treat naturally in VB. For an example
on how to raise events from you python code, you can look at the sample demo
in win32com/demos/connect.py (implements client and server) or in
win32com/server/connect.py (for server implementation. The demo server
inherits from this one)
Last, Mark Hammond respond while ago about COM Server  Events:
http://mail.python.org/pipermail/python-win32/2004-September/002386.html, I
don't know if there are changes...

Regards,

Jorge


On 3/15/07, Gabriel Genellina [EMAIL PROTECTED] wrote:


En Wed, 14 Mar 2007 21:17:12 -0300, Larry Bates [EMAIL PROTECTED]
escribió:

 I have a rather large Python class that I've converted to
 a COM object.  I can dispatch (using either Python or VB)
 and call the methods perfectly.  Now a new client wants
 to call it from Delphi.  Can anyone out there give me
 any pointers on how that would be done.  Are there any
 gotchas about the way arguments or return values
 would need to be different for Delphi.  I have NO Delphi
 experience so I'm completely lost.

The same as he would do for any other COM object. There are tools in
Delphi for building automatically the needed Delphi declarations
(interfases, classes, methods, constants... similar to what makepy does
for Python).
All OLE types work fine. (Variants are a bit hard to process, yes, but it
can be done)

 Secondly, I need a callback function in VB (progress
 meter) that I can pass to Python COM object to show

Sorry, I try to stay away of VB as far as possible :)

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list

RE: Need help with apack compression code

2007-03-16 Thread Sells, Fred
try google: python apack found several 

in general, always google first; python has so many devotees that someone
has generally solved most problems already.

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
Behalf Of priya kale
Sent: Thursday, March 15, 2007 11:33 PM
To: python-list@python.org
Subject: Need help with apack compression code [html-removed]


I need to code for decompressing the file which is compressed using Apack, I
am supposed to code it in visual c++, Plz help me finding algorithm
compatible to Widows based C or c++.

Regards,
 Priya Kale
(Pune)
-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Jan Danielsson
Gerald wrote:
 Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
 curriculum did not include Python programming yet I see many vacancies
 for Python developers.I studied programming Pascal,C++ and Delphi.So I
 need to catch up quickly and master Python programming.How do you
 suggest that I achieve this goal?

   1. Chose a project for yourself
   2. Write it

   I needed a distributed white board application for working on a World
Domination Plan with my friends, so I selected that as a good get to
learn Python project.

 Is python platform independent?

   Mostly..

 What
 is the best way?And how long would it take before I can develop
 applications using python?

   Depends on your learning skills, and what kind of applications we're
talking about.


-- 
Kind regards,
Jan Danielsson
 And now a word from our sponsor --
Want to have instant messaging, and chat rooms, and discussion
groups for your local users or business, you need dbabble!
--  See http://netwinsite.com/sponsor/sponsor_dbabble.htm  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: war with china? a different approach?

2007-03-16 Thread Graeme Glass
Whats this got to do with python?


On Jan 19, 9:34 pm, [EMAIL PROTECTED] wrote:
 Coz we have fools in the govt, the downfall of the US has only been
 accelerated !!
 The are morons who staged 9/11 controlled demolition to kill americans
 to start their idiotic war.

 Date: Sat, 21 Oct 2006 16:12:20 -0500
 Subject: [nsmworld] war with china? a different approach?
 From: J. Knowles [EMAIL PROTECTED]

 Greater China
  Apr 20, 2006

 SPEAKING FREELY
 If it comes to a shooting war ...
 By Victor N Corpus

 Speaking Freely is an Asia Times Online feature that allows guest
 writers to
 have their say. Please click here if you are interested in
 contributing.

 One could call this article a worst-case scenario for the new American
 century. Why worst case? Because of the hard lessons from history. The
 Romans did not consider the worst-case scenario when Hannibal crossed
 the
 Alps with his elephants and routed them; or when Hannibal encircled and

 annihilated the numerically superior Roman army at the Battle of
 Cannae.

 The French did not consider the worst-case scenario at Dien Bien Phu
 and
 when they built the Maginot Line, and the French suffered disastrous
 defeats. The Americans did not consider the

 worst-case scenario at Pearl Harbor or on September 11, and the results
 were
 disastrous for the American people. Again, American planners did not
 consider the worst-case scenario in its latest war
 in Iraq, but instead operated on the best-case scenario, such as
 considering the Iraq invasion a cake walk and that the Iraqi people
 would
 be parading in the streets, throwing flowers and welcoming American
 soldiers
 as liberators, only to discover the opposite.

 Scenario One: America launches 'preventive war' vs China
 Our first objective is to prevent the re-emergence of a new rival. This
 is a
 dominant consideration underlying the new regional defense strategy and

 requires that we endeavor to prevent any hostile power from dominating
 a
 region whose resources would, under consolidated control, be sufficient
 to
 generate global power. These regions include Western Europe, East Asia,
 the
 territory of the former Soviet Union and Southwest Asia.
 -Paul Wolfowitz, former US deputy secretary of defense and currently
 president of the World Bank
 Consider these snapshots of China:

 Since 1978, China has averaged 9.4% annual GDP growth

 It had a five-fold increase in total output per capita from 1982 to
 2002

 It had $61 billion in foreign direct investment in 2004 alone and
 foreign
 trade of $851 billion, the third-largest in the world

 The US trade deficit with China exceeded $200 billion in 2005

 China has $750 billion in foreign exchange reserves and is the
 second-biggest oil importer

 Last year it turned out 442,000 new engineers a year; with 48,000
 graduates
 with master's degrees and 8,000 PhDs annually; compared to only 60,000
 new
 engineers a year in the US.

 China for the first time (2004) surpassed America to export the most
 technology wares around the world. China enjoyed a $34 billion trade
 surplus
 with the US in advanced technology products in 2004 (The Economist,
 December
 17, 2005). In 2005, the surplus increased to $36 billion

 It created 20,000 new manufacturing facilities a year

 It holds $252 billion in US Treasury Bonds (plus $48 billion held by
 Hong
 Kong)

 Among the five basic food, energy and industrial commodities -grain
 and
 meat, oil and coal and steel -consumption in China has eclipsed that
 of the
 US in all but oil.

 China has also gone ahead of the US in the consumption of TV sets,
 refrigerators and mobile phones

 In 1996, China had 7 million cell phones and the US had 44 million. Now

 China has more mobile phone users than the US has people.

 China has about $1 trillion in personal savings and a savings rate of
 close
 to 50%; U.S. has about $158 billion in personal savings and a savings
 rate
 of about 2% (The Wall Street Journal, Nov 19, 2005)
 Shanghai boasts 4,000 skyscrapers - double the number in New York
 City (The
 Wall Street Journal, Nov 19, 2005)
 Songbei, Harbin City in north China is building a city as big as New
 York
 City

 Goldman Sachs predicts that China will surpass the US economy by 2041.

 Before China's economy catches up with America, and before China builds
 a
 military machine that can challenge American superpower status and
 world
 dominance, America's top strategic planners (Project for the New
 American
 Century) decide to launch a preventive war against China. As a
 pretext for
 this, the US instigates Taiwan to declare independence.

 Taiwan declares independence!
 China has anticipated and long prepared itself for this event. After
 observing Operation Summer Pulse -04 when US aircraft carrier
 battle
 groups converged in the waters off China's coast in mid-July through
 August
 of 2004, Chinese planners began preparing to face its own worst-case
 scenario: the possibility of confronting a total of 15 carrier 

Re: Eureka moments in Python

2007-03-16 Thread Jarek Zgoda
Ben Finney napisał(a):

 I'd be interested in hearing people's stories of Eureka moments in
 Python, moments where you suddenly realise that some task which
 seemed like it would be hard work was easy with Python.
 
 I don't recall the exact context, but Python was the language that
 introduced me to the power of a unified type system.
 
 The application I was writing was doing a whole lot of bookkeeping of
 information about what kind of data was being processed, which had to
 be kept updated in parallel with the data itself. Once I realised that
 unified type system and first-class objects meant that I could
 simply store the *type itself* as data, whether a basic type or one of
 my own, things became astoundingly easier. Soon after that I learned
 that functions are also objects, and I was hooked.

This was exactly the same eureka in my case too -- functions are
objects. I can store in a tuple the function and its arguments, then the
only thing I have to do is to call first element with the rest of
elements as arguments. This code now scares people in my former job --
being Java and C++ heads they just cann't get it... ;)

-- 
Jarek Zgoda

We read Knuth so you don't have to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python shell on mac os x

2007-03-16 Thread Bert Heymans
On Mar 16, 4:08 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
 Bert Heymans [EMAIL PROTECTED] wrote:
  Hi!

  I'm using iTerm on the mac the keymapping isn't right. On Linux and
  Windows it's really nice to be able to hit up to get the previous
  command. Does anyone know a way to get the Pyhton shell to work like
  on other systems, I always get this when I hit the direction keys:

   ^[OA^[OC^[OD

  I've been looking for the correct mappings but can't find a proper
  reference online nor what the Python shell expects. Any help would be
  greatly appreciated! Hints/suggestions on keywords to use in a search
  on Google are always welcome :) I don't know where to begin looking
  for this kind of information.

 The Python 2.3.5 bundled with MacOSX doesn't come with readline.
 Download 2.5 (or if you must 2.4) for the Mac fromwww.python.organd
 live happily ever after.

 E.g. (I'm hitting an up-arrow the 2nd time, then control-D next time):

 brain:~ alex$ python2.3
 Python 2.3.5 (#1, Jan 13 2006, 20:13:11)
 [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
 Type help, copyright, credits or license for more information. 2+2
 4
  ^[[A

   File stdin, line 1
 ^
 SyntaxError: invalid syntax ^D

 brain:~ alex$ python2.4
 Python 2.4.3 (#1, Apr  7 2006, 10:54:33)
 [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
 Type help, copyright, credits or license for more information. 2+2
 4
  2+2
 4

 brain:~ alex$

 Alex

Wow, thanks for pointing that out Alex! I wasn't even hoping a
solution could be that simple :s

-- 
http://mail.python.org/mailman/listinfo/python-list


UpNp messages

2007-03-16 Thread ozan SARI

I  want to   sendmessages to a  upnp device ,and  listen to it's
notify messages. Can  I   do that with   Python.   Can  you  help me and
send  an   example?

Thanks



Ozan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Steven Bethard
Marc 'BlackJack' Rintsch wrote:
 In [EMAIL PROTECTED], Paul Rubin wrote:
 
 n00m [EMAIL PROTECTED] writes:
 h = collections.defaultdict(itertools.repeat(0).next)
 Something wrong with 
h = collections.defaultdict(int)
 ?
 
 According to a post by Raymond Hettinger it's faster to use that iterator
 instead of `int`.

Yep. It's because the .next() method takes no arguments, while int() 
takes varargs because you can do::

 int('2')
 int('2', 8)

Calling a no-args function is substantially faster than calling a 
varargs function.

STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread 7stud
The general idiom for altering lines in a file is to open the original
file and write the alterations to a temp file. After you are done
writing to the temp file, delete the original file, and change the
temp file name to the original file name.

If instead you were to read the whole file into a variable, and then
start overwriting the original file with the altered data, if your
program should happen to crash after writing one line to the file, all
the data in your variable would disappear into the ether, and your
file would only contain one line of data.  You can imagine what that
would be like if you had lots of important data in the file.

Here's my attempt that incorporates a temp file:

-
import os

filepath = ./change_files

li = os.listdir(filepath)
for name in li:
fullpath = filepath + / + name
if os.path.isfile(fullpath):
infile = open(fullpath, 'r')

lastDotPos = fullpath.rfind(.)
fileName = fullpath[:lastDotPos]
ext = fullpath[lastDotPos:]
tempName = fileName + ext + .temp

outfile = open(tempName, w)
for line in infile:
outfile.write(line + altered\n)
outfile.close()

os.remove(fullpath)
os.rename(tempName, tempName[:-5])
---

I think it also needs some kind of check to make sure you have
permissions to delete the original file.

-- 
http://mail.python.org/mailman/listinfo/python-list


mySQLdb versus platform problem

2007-03-16 Thread Robin Becker
I am seeing different outcomes from simple requests against a common database 
when run from a freebsd machine and a win32 box.


The test script is
###
import MySQLdb, sys
print sys.version
print MySQLdb.__version__
db=MySQLdb.connect(host='appx',db='sc_0',user='user',passwd='secret',use_unicode=True)
cur=db.cursor()
cur.execute('select * from sc_accomodation where id=31')
data=cur.fetchall()

for i,t in enumerate(data[0]):
 if isinstance(t,(str,unicode)): print i,repr(t)
###

The table in question is charset='latin1', however the original owners put some 
special windows characters in eg 0x92 (a quote).

in the windows version I see this kind of string in the output

2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
1.2.1_p2
.
14 u'Built entirely of mahogany, Acajou seeks to introduce a new concept of
living in the midst of nature on the C\xf4te d\x92Or beach which stretches
along the island\x92s northern coast.\r\n\r\nThe hotel\x92s 24 standard
and 4 superior ro

the freeBSD machine produces

2.4.3 (#2, Sep  7 2006, 09:34:29)
[GCC 3.4.4 [FreeBSD] 20050518]
...
14 u'Built entirely of mahogany, Acajou seeks to introduce a new concept of
living in the midst of nature on the C\xf4te d\u2019Or beach which stretches
along the island\u2019s northern coast.\r\n\r\nThe hotel\u2019s 24 standard
and 4 superior rooms...

so the windows version seems to leave the \x92 as is and the freebsd version 
converts it to its correct value.

This is already bad enough as I expected the outcomes to be the same, but given 
that the encoding of the database is wrong I expected some problems.

However, if I don't have use_unicode=True in the above script I get back 
strings, but this time the difference is larger.

windows
2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
1.2.1_p2
...
2 C\xf4te d'Or\r\nPraslin
...

unix

2.4.3 (#2, Sep  7 2006, 09:34:29)
[GCC 3.4.4 [FreeBSD] 20050518]
1.2.1_p2
..
2 C\xc3\xb4te d'Or\r\nPraslin
...

so here the returned string appears to have been automatically converted to 
utf8.


My questions are

1) why the difference in the unicode version?
2) why does the unix version convert to utf8?

The database being common it seems it's either the underlying libraries or the 
compiled extension or python that causes these differences, but which?
-- 
Robin Becker

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To count number of quadruplets with sum = 0

2007-03-16 Thread Paul Rubin
Steven Bethard [EMAIL PROTECTED] writes:
  According to a post by Raymond Hettinger it's faster to use that
  iterator instead of `int`.
 Yep. It's because the .next() method takes no arguments, while int()
 takes varargs because you can do:: ...

Heh, good point.  Might be worth putting a special hack in defaultdict
to recognize the common case of defaultdict(int).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distributing python software in jar like fashion

2007-03-16 Thread John Nagle
 Were Python eggs a flop, or what?

 We need to have one packager that everyone agrees on.
Otherwise, installs become a mess, and then you have to have
installers that handle multiple packagers.

John Nagle

Gary Duzan wrote:
 In article [EMAIL PROTECTED], alf  [EMAIL PROTECTED] wrote:
 
Hi,

I have a small app which consist of a few .py files. Is there any way to 
distribute it in jar like fashion as a single file I can just run python 
on. I obviously look for platform independent solution.

Thx in advance, A.
 
 
There is a new package that has been discussed here recently
 called Squisher that should do what you want by packing things into
 a single pyc file. There are still some minor issues that need to
 be ironed out with running the pyc directly, but it should do
 exactly what you want Real Soon Now.
 
 http://groups.google.com/groups/search?q=group%3Acomp.lang.python+squisherqt_s=Search
 
   Gary Duzan
   Motorola CHS
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread 7stud
On Mar 16, 9:38 am, 7stud [EMAIL PROTECTED] wrote:
 -
 import os

 filepath = ./change_files

 li = os.listdir(filepath)
 for name in li:
 fullpath = filepath + / + name
 if os.path.isfile(fullpath):
 infile = open(fullpath, 'r')

 lastDotPos = fullpath.rfind(.)
 fileName = fullpath[:lastDotPos]
 ext = fullpath[lastDotPos:]
 tempName = fileName + ext + .temp

 outfile = open(tempName, w)
 for line in infile:
 outfile.write(line + altered\n)
 outfile.close()

 os.remove(fullpath)
 os.rename(tempName, tempName[:-5])
 ---


I did some unnecessary name manipulation in there.  Try this:

filepath = ./change_files

li = os.listdir(filepath)
for name in li:
fullpath = filepath + / + name
if os.path.isfile(fullpath):
infile = open(fullpath, 'r')

tempName = fullpath + .temp
outfile = open(tempName, w)
for line in infile:
outfile.write(line + altered\n)
outfile.close()

os.remove(fullpath)
os.rename(tempName, tempName[:-5])

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a simple crypto library

2007-03-16 Thread Pınar Yanardağ

yep, thanx a lot ;)

2007/3/15, hg [EMAIL PROTECTED]:


Paul Rubin wrote:

 tlslite

cool !

--
http://mail.python.org/mailman/listinfo/python-list





--
Pınar pinguar Yanardağ
http://pinguar.org
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Importing

2007-03-16 Thread HMS Surprise
Thanks for posting. I continued to read and realized the instantiation
was not a function call soon after I posted. Oh well...

Still unsure about the best way to break up the large #start - #end
section. I appreciate your answers and try to digest them more fully.
Then maybe I will have a better idea and can post better qualified/
quantified questions.

Thanks again,

jh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mastering Python

2007-03-16 Thread Diez B. Roggisch
Dennis Lee Bieber wrote:

 On 16 Mar 2007 04:41:38 -0700, Gerald [EMAIL PROTECTED] declaimed
 the following in comp.lang.python:
 
 Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my
 curriculum did not include Python programming yet I see many vacancies
 for Python developers.I studied programming Pascal,C++ and Delphi.So I
 
 blinkblink
 
 Pardon my surprise, but what school only covers simple Pascal,
 Object Pascal (in the guise of Delphi), and C++ without at least
 introducing other languages. Three fairly similar languages (with the
 same similar flaws -- like needing to remember to put begin/end ({})
 around multi-line blocks...

Nowadays, you can get through CS graduate studies with only Java. Sad, but
true.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eureka moments in Python

2007-03-16 Thread Sion Arrowsmith
Paul McGuire [EMAIL PROTECTED] wrote:
On Mar 13, 2:16 am, Steven D'Aprano [EMAIL PROTECTED]
wrote:
 I'd be interested in hearing people's stories of Eureka moments in Python,
 moments where you suddenly realise that some task which seemed like it
 would be hard work was easy with Python.
The day I wrote a CORBA method intercepter in 8 lines of code [ ... ]

This is more a batteries included eureka moment than a Python one,
but writing a fetchmail substitute in 6 lines was an eye-opener.

-- 
\S -- [EMAIL PROTECTED] -- 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: getopt or optparse options/arguments wrapping?

2007-03-16 Thread Steven Bethard
Rocky Zhou wrote:
 I wonder is there any way to make the wrapper program can wrap options
  arguments for the  the  subprocess/command the wrapper will
 execute? by getopt or optparse module?
[snip]
 I need this because I now have finished a fs_backup script written in
 python, it will execute tar  find to complete full and
 differentiating/incremental backup for the file system level files,
 and their restoring. This script will do different things by the
 command line arguments, and execute find/tar in different ways, but
 for being more flexible, I want some options of tar/find can also been
 specified from the command line directly, and the script just transmit
 those to tar/find simply.

I'm not clear on exactly what it is you want.  Are you trying to do
something like::

fs_backup --foo --bar x y z --tar-foo --tar-bar tx ty tz

where ``--foo --bar x y z`` gets handled by your command and ``--tar-foo
--tar-bar tx ty tz`` gets passed on through to the tar command?

STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list

Python training in Barcelona, Spain?

2007-03-16 Thread xavim
Hi!

I work for a company located in Barcelona, Spain, and we are
looking for an on-site introductory Python training.  The
audience would consist of about 10 developers with Java
background.  The training should be taught in Spanish.

Does anyone knows of a company or individual that could
deliver such training?

Thanks!
Xavi

-- 
http://mail.python.org/mailman/listinfo/python-list


TypeError: 'module' object is not callable

2007-03-16 Thread randomtalk
Hello everyone!
i have the following test code:
class temp:
def __init__(self):
self.hello = hello world!
def printworld(self):
print(self.hello)
t = temp()

and i tried to call profile('t.printworld()')

but i received the following error:
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: 'module' object is not callable

I'm not sure what is wrong exactly, if anyone can point me to the
right direction, it would be much appreciated!

-- 
http://mail.python.org/mailman/listinfo/python-list


Finding the insertion point in a list

2007-03-16 Thread tkpmep
I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
positive integer y, I want to determine its appropriate position in
the list (i.e the point at which I would have to insert it in order to
keep the list sorted. I can clearly do this with a series of if
statements:

if yx[1]:
n = 0
elif y  x[2]:
n = 1
elif y  x[3]:
n = 2
else:
n = 3

Or with a generator comprehension
n  = sum ( yx[i] for i in range(len(x)) ) - 1

But there  has to be a cleaner way, as the first approach is unwieldy
and does not adapt to changing list lengths, and the second is not
obvious to a casual reader of the code.

My list will typically have 2 to 5 items, so speed is not a huge
issue. I'd appreciate your guidance.

Sincerely

Thomas Philips

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread Matimus
You might look at the bisect module (part of the standard
distribution).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distributing python software in jar like fashion

2007-03-16 Thread Robert Kern
John Nagle wrote:
  Were Python eggs a flop, or what?

No.

  We need to have one packager that everyone agrees on.
 Otherwise, installs become a mess, and then you have to have
 installers that handle multiple packagers.

Eggs and Squisher are complementary tools. Squisher is good for distributing an
application with all of its dependencies in a single file; it is not a packager
or installer for libraries. Eggs are good for distributing libraries and plugins
and their dependencies.

-- 
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distributing python software in jar like fashion

2007-03-16 Thread Chris Cioffi
Hi John,

I don't think eggs are a flop, however the pain they are trying to
solve is generally pretty minor in the Python world vs what we often
see with other languages.  We're starting to see some push to move
more 3rd party libraries and frameworks to eggs (ie:  Turbogears) and
as the developers get used to dealing with eggs we will reach a
critical mass.

The 2 main things holding eggs back, imo:
1.  The eggs extensions aren't included in the Python std lib.
2.  The Python std lib is fairly robust and we can accomplish a
significant amount of work without needing 3rd party code.

If eggs were included in the std lib, and/or the std lib was packaged
as eggs we'd see a far more rapid uptake.  The key is getting the egg
extensions into the main distribution.

Chris

On 3/16/07, John Nagle [EMAIL PROTECTED] wrote:
  Were Python eggs a flop, or what?

  We need to have one packager that everyone agrees on.
 Otherwise, installs become a mess, and then you have to have
 installers that handle multiple packagers.

 John Nagle

 Gary Duzan wrote:
  In article [EMAIL PROTECTED], alf  [EMAIL PROTECTED] wrote:
 
 Hi,
 
 I have a small app which consist of a few .py files. Is there any way to
 distribute it in jar like fashion as a single file I can just run python
 on. I obviously look for platform independent solution.
 
 Thx in advance, A.
 
 
 There is a new package that has been discussed here recently
  called Squisher that should do what you want by packing things into
  a single pyc file. There are still some minor issues that need to
  be ironed out with running the pyc directly, but it should do
  exactly what you want Real Soon Now.
 
  http://groups.google.com/groups/search?q=group%3Acomp.lang.python+squisherqt_s=Search
 
Gary Duzan
Motorola CHS
 
 
 --
 http://mail.python.org/mailman/listinfo/python-list



-- 
A little government and a little luck are necessary in life, but only
a fool trusts either of them. -- P. J. O'Rourke
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread kyosohma
On Mar 16, 12:59 pm, [EMAIL PROTECTED] wrote:
 I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
 positive integer y, I want to determine its appropriate position in
 the list (i.e the point at which I would have to insert it in order to
 keep the list sorted. I can clearly do this with a series of if
 statements:

 if yx[1]:
 n = 0
 elif y  x[2]:
 n = 1
 elif y  x[3]:
 n = 2
 else:
 n = 3

 Or with a generator comprehension
 n  = sum ( yx[i] for i in range(len(x)) ) - 1

 But there  has to be a cleaner way, as the first approach is unwieldy
 and does not adapt to changing list lengths, and the second is not
 obvious to a casual reader of the code.

 My list will typically have 2 to 5 items, so speed is not a huge
 issue. I'd appreciate your guidance.

 Sincerely

 Thomas Philips

One way to do this would be to use the cmp built-in and loop over the
items in the list. Maybe something like this:

x = [0, 100, 200, 1000]
numLst = len(x)
count = 0
for i in range(numLst):
resultOfCmp = cmp(newNum, x[count])
if resultOfCmp == -1:
print i
x.insert(count, newNum)
break
count += 1

# Where newNum is the one to be inserted.

It's a hack, but it might get the ol' creative juices flowing.

Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'module' object is not callable

2007-03-16 Thread kyosohma
On Mar 16, 12:42 pm, [EMAIL PROTECTED] wrote:
 Hello everyone!
 i have the following test code:
 class temp:
 def __init__(self):
 self.hello = hello world!
 def printworld(self):
 print(self.hello)
 t = temp()

 and i tried to call profile('t.printworld()')

 but i received the following error:
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: 'module' object is not callable

 I'm not sure what is wrong exactly, if anyone can point me to the
 right direction, it would be much appreciated!



If you're using the profile module, you need to do something like

profile.run('t.printworld()')

Good luck,

Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Determining cause of termination

2007-03-16 Thread Yang
Hi all, my Python (2.4) program crashed after a couple days of running
(this'll be a pain to debug, I know). I think it just...stopped
running. My log files didn't show any (unusual) exceptions (I use the
logging module to files and stdout/stderr piped to files). I have a
feeling that the python interpreter crashed - perhaps I consumed a lot
of memory and so CPython died. I also don't use ctypes or anything - I
do import some twisted modules but I don't really use them. There was
no core dump and I don't know how to elicit one. How can I find out as
much as possible what happened? For starters, I'm now checking exit
status and periodically running 'top' to monitor memory consumption,
but are there any other ideas?

Thanks in advance,

Yang
-- 
http://mail.python.org/mailman/listinfo/python-list


Displaying EPS in a GUI

2007-03-16 Thread virtk0s
Does anybody know of a good way to display Encapsulated Postscript
images in a GUI? I'm currently using wx, but would be perfectly
willing to switch to another binding to keep the program from becoming
hackish.

Thanks!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'module' object is not callable

2007-03-16 Thread 7stud
Hi,

I can't find any documentation on the profile() function.  But it
might take a function reference as an argument and not the string you
are feeding it.  For instance:

profile(t.printworld)

Note the difference between:

t.printworld
t.printworld()

The latter executes the function and then replaces the function call
with the return value of the function.

-- 
http://mail.python.org/mailman/listinfo/python-list


MySQLdb collectable memory leak

2007-03-16 Thread John Nagle
It's not big, but it's there.  Just attaching to a MySQL
database with MySQLdb, then closing the connection without
doing anything results in some collectable garbage:

gc: collectable cell 00DCDB30
gc: collectable function 00DC2D70
gc: collectable tuple 00DBAD78
gc: collectable tuple 00D73790
gc: collectable dict 00E81150

(Python 2.4, MySQL 5, Windows 2000)

(For test purposes, I run with GC turned off, so if any
memory leaks, collectable or otherwise, are introduced, they're noticed.)

John Nagle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread Paul McGuire
On Mar 16, 12:59 pm, [EMAIL PROTECTED] wrote:
 I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
 positive integer y, I want to determine its appropriate position in
 the list (i.e the point at which I would have to insert it in order to
 keep the list sorted. I can clearly do this with a series of if
 statements:

 if yx[1]:
 n = 0
 elif y  x[2]:
 n = 1
 elif y  x[3]:
 n = 2
 else:
 n = 3

 Or with a generator comprehension
 n  = sum ( yx[i] for i in range(len(x)) ) - 1

 But there  has to be a cleaner way, as the first approach is unwieldy
 and does not adapt to changing list lengths, and the second is not
 obvious to a casual reader of the code.

 My list will typically have 2 to 5 items, so speed is not a huge
 issue. I'd appreciate your guidance.

 Sincerely

 Thomas Philips

List will typically have 2 to 5 items?  Keep it simple!

x.append(y)
x.sort()

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mySQLdb versus platform problem

2007-03-16 Thread John Nagle
Try:

 db=MySQLdb.connect(host='appx',db='sc_0',user='user',passwd='secret',
use_unicode=True, charset = utf8)

The distinction is that use_unicode tells Python to convert to Unicode,
but Python doesn't know the MySQL table type.  'charset=utf8' tells
MySQL to do the conversion to UTF8, which can be reliably converted
to Unicode.

John Nagle

Robin Becker wrote:
 I am seeing different outcomes from simple requests against a common 
 database when run from a freebsd machine and a win32 box.
 
 
 The test script is
...
 db=MySQLdb.connect(host='appx',db='sc_0',user='user',passwd='secret',use_unicode=True)
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread hiro
Thanks a lot for the help guys, I'm at work right now and I will go
over your suggestions one by one this weekend.  Being more alert now,
taking a look at the examples you posted, I now see how to approach
this problem.  The thing with python that I'm starting to realize is
that there are a million different ways to approach a problem, so I
find it great for experimenting (when time allows) yet very
challenging to choose an approach.

Cheers,

h.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python noob, multiple file i/o

2007-03-16 Thread hiro
Thanks a lot for the help guys, I'm at work right now and I will go
over your suggestions one by one this weekend.  Being more alert now,
taking a look at the examples you posted, I now see how to approach
this problem.  The thing with python that I'm starting to realize is
that there are a million different ways to approach a problem, so I
find it great for experimenting (when time allows) yet very
challenging to choose an approach.

Cheers,

h.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread kyosohma
On Mar 16, 2:32 pm, Paul McGuire [EMAIL PROTECTED] wrote:
 On Mar 16, 12:59 pm, [EMAIL PROTECTED] wrote:



  I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
  positive integer y, I want to determine its appropriate position in
  the list (i.e the point at which I would have to insert it in order to
  keep the list sorted. I can clearly do this with a series of if
  statements:

  if yx[1]:
  n = 0
  elif y  x[2]:
  n = 1
  elif y  x[3]:
  n = 2
  else:
  n = 3

  Or with a generator comprehension
  n  = sum ( yx[i] for i in range(len(x)) ) - 1

  But there  has to be a cleaner way, as the first approach is unwieldy
  and does not adapt to changing list lengths, and the second is not
  obvious to a casual reader of the code.

  My list will typically have 2 to 5 items, so speed is not a huge
  issue. I'd appreciate your guidance.

  Sincerely

  Thomas Philips

 List will typically have 2 to 5 items?  Keep it simple!

 x.append(y)
 x.sort()

 -- Paul

I thought doing an append and sort was a good idea too, but the
question entailed knowing the insertion point, so I skipped it.
Thanks!

-- 
http://mail.python.org/mailman/listinfo/python-list


socket.error: (9, 'Bad file descriptor') Python 2.5

2007-03-16 Thread Brian G. Merrell

I'm getting the following trace in python 2.5:

Traceback (most recent call last):
 File ./template_unittest.py, line 36, in module
   zencc.start_browser(machines.zones[0].devices.get_primary_servers()[0])
 File /home/bean/code/automation/nrm-qa/trunk/brimstone/lib/zcc.py, line
221, in start_browser
   self.t.StartWebBrowser(url)
 File /home/bean/code/automation/tomato/Tomato/selenium.py, line 140, in
StartWebBrowser
   res = self.sendcommand('open', url)
 File /home/bean/code/automation/tomato/Tomato/selenium.py, line 64, in
_sendcommand
   return self.gateway.execute(selcmd, str(seltarget), str(selvalue))
 File /home/bean/code/automation/tomato/Tomato/SeleniumGateway.py, line
137, in execute
   self.send_string(self.buildselenese(selcmd, seltarget, selvalue))
 File /home/bean/code/automation/tomato/Tomato/SeleniumGateway.py, line
161, in send_string
   self.waiting_client.write(command)
 File /usr/lib/python2.5/socket.py, line 261, in write
 File /usr/lib/python2.5/socket.py, line 248, in flush
socket.error: (9, 'Bad file descriptor')

However, I do not have any problems when using Python 2.4.  In fact, I can
replace the socket.py library from 2.5 with the socket.py from 2.4 and it
fixes this problem.  I ran a diff on the two different sockey.py versions,
and there are some differences but I couldn't see anything obvious that
would cause this.

Any ideas?  I can post more code if necessary.

Also, here are the versions I'm using:

Python 2.5 (r25:51908, Jan  9 2007, 16:59:32)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2

Python 2.4.4 (#1, Mar 15 2007, 23:58:13)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2

Thanks,
Brian
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: To count number of quadruplets with sum = 0

2007-03-16 Thread marek . rocki
My attempt uses a different approach: create two sorted arrays, n^2
elements each; and then iterate over them looking for matching
elements (only one pass is required). I managed to get 58,2250612857 s
on my 1,7 MHz machine. It requires numpy for decent performance,
though.

import numpy
import time

def parse_input():
al, bl, cl, dl = [], [], [], []
for i in xrange(int(raw_input())):
a, b, c, d = map(int, raw_input().split())
al.append(a)
bl.append(b)
cl.append(c)
dl.append(d)
return al, bl, cl, dl

def count_zero_sums(al, bl, cl, dl):
n = len(al) # Assume others are equal

# Construct al extended (every element is repeated n times)
ale = numpy.array(al).repeat(n)
del al
# Construct bl extended (whole array is repeated n times)
ble = numpy.zeros((n*n,), int)
for i in xrange(n): ble[i*n:(i+1)*n] = bl
del bl
# Construct abl - sorted list of all sums of a, b for a, b in al, bl
abl = numpy.sort(ale + ble)
del ale, ble

# Construct cl extended (every element is repeated n times)
cle = numpy.array(cl).repeat(n)
del cl
# Construct dl extended (whole array is repeated n times)
dle = numpy.zeros((n*n,), int)
for i in xrange(n): dle[i*n:(i+1)*n] = dl
del dl
# Construct cdl - sorted list of all negated sums of a, b for a, b in
cl, dl
cdl = numpy.sort(-(cle + dle))
del cle, dle

# Iterate over arrays, count matching elements
result = 0
i, j = 0, 0
n = n*n
try:
while True:
while abl[i]  cdl[j]:
i += 1
while abl[i]  cdl[j]:
j += 1
if abl[i] == cdl[j]:
# Found matching sequences
ii = i + 1
while ii  n and abl[ii] == abl[i]: ii += 1
jj = j + 1
while jj  n and cdl[jj] == cdl[j]: jj += 1
result += (ii - i)*(jj - j)
i, j = ii, jj
except IndexError:
pass

return result

t = time.clock()
print count_zero_sums(*parse_input())
print time.clock() - t

-- 
http://mail.python.org/mailman/listinfo/python-list


python global variable error

2007-03-16 Thread ANIL KARADAĞ

hi, i made a program in python but received global name  error. the program
code;
 serverhost = '127.0.0.1'
   serverport = 2000
   BUFSIZ = 1024
   addr = (serverhost,serverport)
   if str(sys.argv).find(-s) == -1:
   cs = socket(AF_INET, SOCK_STREAM,0) # create a TCP socket
   cs.connect(addr)
   key=1
   main()
   else:
   serversock = socket(AF_INET, SOCK_STREAM)# create a TCP socket
   serversock.bind(addr)
   serversock.listen(2)
   key=2
   print 'waiting for connection…'
   while 1:
   clientsock, addr = serversock.accept()
   print '…connected from:', addr,clientsock
   main()
   serversock.close()

what is difference cs and clientsock? i use cs in main() function or others,
but  don't use clientsock not call from main()   data = clientsock.recv(BUFSIZ)
NameError: global name 'clientsock' is not defined 

i am sorry, i  little know english
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Finding the insertion point in a list

2007-03-16 Thread 7stud
How about:

---
x = [0, 100, 200, 1000]
y = -1
inserted = False

for i in range(len(x)):
if(y = x[i]):
x.insert(i, y)
inserted = True
break
if(not inserted): x.append(y)

print x


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning other instance from __init__

2007-03-16 Thread Paulo da Silva
Paulo da Silva escreveu:
 Alex Martelli escreveu:
 Paulo da Silva [EMAIL PROTECTED] wrote:
 
 
 E.g.:

 class C1(object):
 def __new__(cls, xxx):
 if xxx: return type.__new__(cls, xxx)
 else: return C1.load(xxx)
 @staticmethod
  def load(xxx): return ...whatever...
  def __init__(self, xxx):
  if hasattr(self, 'foo'): return
  self.foo = 'foo'
  self.bar = 'bar'

 
 
 Just for a better understanding ...
 Can I do this?
 
 class C1(object):
 def __new__(cls, xxx):
 if xxx:
   cls.foo='foo'
   cls.bar='bar'
   return type.__new__(cls, xxx)
This does not work(!) at least for python 2.4.3.

 else:
   return C1.load(xxx)
 @staticmethod
 def load(xxx): return ...whatever...
 # OMMIT THE __init__
 # or
 def __init__(self, xxx):
 pass

I needed return cls and put the __init__ stuff here.
Is this the best practice?

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread Matimus
On Mar 16, 11:20 am, Matimus [EMAIL PROTECTED] wrote:
 You might look at the bisect module (part of the standard
 distribution).

Here is an example:

 from bisect import insort
 x = [0,100,200,1000]
 insort(x,10)
 x
[0, 10, 100, 200, 1000]

-- 
http://mail.python.org/mailman/listinfo/python-list


How to get the previous line in a file?

2007-03-16 Thread Qilong Ren
Hi,all

I am new to this list. And I am glade I am here.
I have a question. I need to do some text processing. I need to read from a 
file line by line. If some line is met with some condition, the previous line 
needs some modification. How to get the info of the previous line? 

Thanks!
Qilong




 

8:00? 8:25? 8:40? Find a flick in no time 
with the Yahoo! Search movie showtime shortcut.
http://tools.search.yahoo.com/shortcuts/#news-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Sharing Objects in Python

2007-03-16 Thread Christoph Haas
On Friday 16 March 2007 12:41, Clement wrote:
 Can a object sharable by two different python programs... If so can you
 please explain... because my project needs two programs to access nearly
 45GB file Symentaniously...

What kind of information is that? Can you put it into a database?

 Christoph
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the insertion point in a list

2007-03-16 Thread tobiaskk
Or like this:

x = [0, 100, 200, 1000]
y = 435
for n, i in enumerate(x):
if y  i:
n = n - 1
break
x.insert(n + 1, y)

If you decide to stick with

n = sum ( yx[i] for i in range(len(x)) ) - 1

Replace it with:

n = sum(y  i for i in x) - 1

Tobias K.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the previous line in a file?

2007-03-16 Thread Shane Geiger
lines = open('/tmp/foo.py', 
r).read().splitlines()

previous_line = 
''  

for line in 
lines:  

   if foo in 
line:   

   print found foo in the current line.  The previous line is:   
+ 
previous_line 

   previous_line = 
line




Qilong Ren wrote:

Hi,all

I am new to this list. And I am glade I am here.
I have a question. I need to do some text processing. I need to read 
from a file line by line. If some line is met with some condition, the 
previous line needs some modification. How to get the info of the 
previous line?


Thanks!
Qilong


Never miss an email again!
Yahoo! Toolbar 
http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolbar/features/mail/ 
alerts you the instant new Mail arrives. Check it out. 
http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/features/mail/


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get the previous line in a file?

2007-03-16 Thread Qilong Ren
Hi, Shane,

Thanks for fast reply.

What I used is :
   for line in open(FILE):
   do stuff
I don't want to store all lines in a list because sometimes the file is very 
large. We need to store the value of the previous line in a variable. Is that 
right? 

Thanks,Qilong

- Original Message 
From: Shane Geiger [EMAIL PROTECTED]
To: Qilong Ren [EMAIL PROTECTED]
Sent: Friday, March 16, 2007 1:51:09 PM
Subject: Re: How to get the previous line in a file?

lines = open('/tmp/foo.py', 
r).read().splitlines()


previous_line = 
''  


for line in 
lines:  


if foo in 
line:   


print found foo in the current line.  The previous line is:   
+ 
previous_line 






Qilong Ren wrote:
 Hi,all

 I am new to this list. And I am glade I am here.
 I have a question. I need to do some text processing. I need to read 
 from a file line by line. If some line is met with some condition, the 
 previous line needs some modification. How to get the info of the 
 previous line?

 Thanks!
 Qilong

 
 Never miss an email again!
 Yahoo! Toolbar 
 http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolbar/features/mail/
  
 alerts you the instant new Mail arrives. Check it out. 
 http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/features/mail/

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy


begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard








 

Bored stiff? Loosen up... 
Download and play hundreds of games for free on Yahoo! Games.
http://games.yahoo.com/games/front-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get the previous line in a file?

2007-03-16 Thread kyosohma
On Mar 16, 3:51 pm, Shane Geiger [EMAIL PROTECTED] wrote:
 lines = open('/tmp/foo.py',
 r).read().splitlines()

 previous_line =
 ''

 for line in
 lines:

 if foo in
 line:

 print found foo in the current line.  The previous line is:  
 +
 previous_line

 previous_line =
 line



 Qilong Ren wrote:
  Hi,all

  I am new to this list. And I am glade I am here.
  I have a question. I need to do some text processing. I need to read
  from a file line by line. If some line is met with some condition, the
  previous line needs some modification. How to get the info of the
  previous line?

  Thanks!
  Qilong

  
  Never miss an email again!
  Yahoo! Toolbar
  http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolb...
  alerts you the instant new Mail arrives. Check it out.
  http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolb...

 --
 Shane Geiger
 IT Director
 National Council on Economic Education
 [EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

 Leading the Campaign for Economic and Financial Literacy

  sgeiger.vcf
 1KDownload

Hi,

You should be able to use the file object's seek and tell methods. Or,
since you're using a list, you could use a counter and when the text
is found, you can print the previous line by subtracting one from the
counter.

counter = 0
for line in lines:
   if 'foo' == line:
  print 'found line. the previous line is: ' %s (lines[counter-1])
   counter += 1

# Or something like that. Experiment!

Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the previous line in a file?

2007-03-16 Thread Paul McGuire
On Mar 16, 3:51 pm, Shane Geiger [EMAIL PROTECTED] wrote:
 lines = open('/tmp/foo.py',
 r).read().splitlines()  
   

 previous_line =
 ''
   

 for line in
 lines:
   

 if foo in
 line: 
  

 print found foo in the current line.  The previous line is:  
 +
 previous_line

 previous_line =
 line  
   





 Qilong Ren wrote:
  Hi,all

  I am new to this list. And I am glade I am here.
  I have a question. I need to do some text processing. I need to read
  from a file line by line. If some line is met with some condition, the
  previous line needs some modification. How to get the info of the
  previous line?

  Thanks!
  Qilong

  
  Never miss an email again!
  Yahoo! Toolbar
  http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolb...
  alerts you the instant new Mail arrives. Check it out.
  http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolb...

 --
 Shane Geiger
 IT Director
 National Council on Economic Education
 [EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

 Leading the Campaign for Economic and Financial Literacy

  sgeiger.vcf
 1KDownload- Hide quoted text -

 - Show quoted text -

If the list is not long, zip the lines together in pairs:

lines = 
test1
test2
foo
test3
test4
.split(\n)

for prev,curr in zip(lines[:-1],lines[1:]):
if foo in curr:
break
else:
prev = not found
print line before foo is:, prev

prints:
line before foo is: test2

-- Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the previous line in a file?

2007-03-16 Thread Jerry Hill
On 3/16/07, Qilong Ren [EMAIL PROTECTED] wrote:
 I have a question. I need to do some text processing. I need to read from a
 file line by line. If some line is met with some condition, the previous
 line needs some modification. How to get the info of the previous line?

I would do something like the following:

inFile = open(LICENSE.txt)

prev_line = None
for line in inFile:
if foo in line:
print prev_line
print line
prev_line = line
inFile.close()

-- 
Jerry
-- 
http://mail.python.org/mailman/listinfo/python-list


Executing a list of functions

2007-03-16 Thread HMS Surprise

Seems to me that one should be able to put the names of several
functions in a list and then have the list executed. But it seems the
output of the functions is hidden, only their return value is visible.
Is this because the list execution is another scope?

Thanx,

jh



def a():
print this is a

def b():
print this is b

lst = [a(), b()]

lst

-- 
http://mail.python.org/mailman/listinfo/python-list


SQLite3, data not found

2007-03-16 Thread jim-on-linux

Python help,

I just started working with SQLite3 and ran into 
this problem.

Below, the first select produces results but, 
after closing then re-opening the database the 
select produces an empty list.  Anyone know the 
reason ??

The table seems to be empty.

  

import sqlite3
con = sqlite3.connect('myData')
cursor = con.cursor()

cursor.execute (create table data
   (recordNo varchar,
   caseNo varchar));

record = ['A', 'B']

cursor.execute(insert into data values (?,?),  
record ) ;

cursor.execute(select * from data );
print cursor.fetchall(); 
con.close()

con = sqlite3.connect('myData')
cursor = con.cursor()
cursor.execute(select * from data);
print cursor.fetchall(); 


jim-on-linux
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing a list of functions

2007-03-16 Thread 7stud
lst = [a, b]

The () symbol causes the named function to execute, and a function
call in the code is always replaced by the function's return value.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mySQLdb versus platform problem

2007-03-16 Thread Robin Becker
John Nagle wrote:
 Try:
 
 db=MySQLdb.connect(host='appx',db='sc_0',user='user',passwd='secret',
 use_unicode=True, charset = utf8)
 
 The distinction is that use_unicode tells Python to convert to Unicode,
 but Python doesn't know the MySQL table type.  'charset=utf8' tells
 MySQL to do the conversion to UTF8, which can be reliably converted
 to Unicode.
 
 John Nagle
 
...

OK that seems to help. However, my database has tables with different 
encodings. Does MySQLdb ignore the table encoding? That would be a bit lame.

Also it still doesn't  explain the different behaviours between unix  
win32 (or perhaps different defaults are somehow magically decided upon).
-things were so much easier when bytes were bytes-ly yrs-
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing a list of functions

2007-03-16 Thread 7stud
On Mar 16, 3:59 pm, 7stud [EMAIL PROTECTED] wrote:
 lst = [a, b]

 The () symbol causes the named function to execute, and a function
 call in the code is always replaced by the function's return value.

Try this:

--
def a():
print this is a

def b():
print this is b

lst = [a(), b()]
--

To create the list, the terms inside the list have to be evaluated.
That causes a and b to execute, and the function calls are replaced by
the each function's return value.  Since your functions don't have a
return statement, the value None is returned.  To see that, add this
line:

print lst


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the previous line in a file?

2007-03-16 Thread dhn
On Mar 16, 5:10 pm, [EMAIL PROTECTED] wrote:
 On Mar 16, 3:51 pm, Shane Geiger [EMAIL PROTECTED] wrote:



  lines = open('/tmp/foo.py',
  r).read().splitlines()

  previous_line =
  ''

  for line in
  lines:

  if foo in
  line:

  print found foo in the current line.  The previous line is:  
  +
  previous_line

  previous_line =
  line

  Qilong Ren wrote:
   Hi,all

   I am new to this list. And I am glade I am here.
   I have a question. I need to do some text processing. I need to read
   from a file line by line. If some line is met with some condition, the
   previous line needs some modification. How to get the info of the
   previous line?

   Thanks!
   Qilong

   
   Never miss an email again!
   Yahoo! Toolbar
   http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolb...
   alerts you the instant new Mail arrives. Check it out.
   http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolb...

  --
  Shane Geiger
  IT Director
  National Council on Economic Education
  [EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

  Leading the Campaign for Economic and Financial Literacy

   sgeiger.vcf
  1KDownload

 Hi,

 You should be able to use the file object's seek and tell methods. Or,
 since you're using a list, you could use a counter and when the text
 is found, you can print the previous line by subtracting one from the
 counter.

 counter = 0
 for line in lines:
if 'foo' == line:
   print 'found line. the previous line is: ' %s (lines[counter-1])
counter += 1

 # Or something like that. Experiment!

 Mike

A more pythonic solution makes use of enumerate().

for number, line in enumerate(lines):
if line == 'foo':
print 'found line. the previous line is: %s' % lines[number -
1]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SQLite3, data not found

2007-03-16 Thread jim-on-linux



from John Clark
use con.commit()

Thanks John, 
this works
jim-on-linux




On Friday 16 March 2007 17:55, jim-on-linux wrote:
 Python help,

 I just started working with SQLite3 and ran
 into this problem.

 Below, the first select produces results but,
 after closing then re-opening the database the
 select produces an empty list.  Anyone know the
 reason ??

 The table seems to be empty.



 import sqlite3
 con = sqlite3.connect('myData')
 cursor = con.cursor()

 cursor.execute (create table data
(recordNo varchar,
caseNo varchar));

 record = ['A', 'B']

 cursor.execute(insert into data values (?,?),
 record ) ;

 cursor.execute(select * from data );
 print cursor.fetchall();
 con.close()

 con = sqlite3.connect('myData')
 cursor = con.cursor()
 cursor.execute(select * from data);
 print cursor.fetchall();


 jim-on-linux
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >