[issue39120] pyodbc dll load failed

2019-12-22 Thread Neil Faulkner


New submission from Neil Faulkner :

Please can someone advise as to the root cause of this error?

--
components: Library (Lib)
files: DLL.PNG
messages: 358796
nosy: nf00038
priority: normal
severity: normal
status: open
title: pyodbc dll load failed
type: compile error
versions: Python 3.8
Added file: https://bugs.python.org/file48800/DLL.PNG

___
Python tracker 
<https://bugs.python.org/issue39120>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Best method for a menu in a command line program?

2010-11-04 Thread braden faulkner
Sorry, I wasn't aware it was doing that but... I've removed it :-)

Sorry about that,
Braden Faulkner
-- 
http://mail.python.org/mailman/listinfo/python-list


Best method for a menu in a command line program?

2010-11-03 Thread braden faulkner
I'm using a menu for my command line app using this method.

choice = foobar
while choice != q:
if choice == c:
temp = input(Celsius temperature:)
print Fahrenheit:,celsius_to_fahrenheit(temp)
elif choice == f:
temp = input(Fahrenheit temperature:)
print Celsius:,fahrenheit_to_celsius(temp)
elif choice != q:
print_options()
choice = raw_input(option:)

Just wondering if there is another or more efficient way I should be doing it?

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


RE: text file reformatting

2010-10-31 Thread Braden Faulkner

I also am having issues with this.

 Date: Sun, 31 Oct 2010 14:48:09 -0500
 From: python.l...@tim.thechases.com
 To: iwawi...@gmail.com
 Subject: Re: text file reformatting
 CC: python-list@python.org
 
  PRJ01001 4 00100END
  PRJ01002 3 00110END
 
  I would like to pick only some columns to a new file and put them to a
  certain places (to match previous data) - definition file (def.csv)
  could be something like this:
 
  VARIABLEFIELDSTARTS FIELD SIZE  NEW PLACE IN NEW DATA FILE
  ProjID  ;   1   ;   5   ;   1
  CaseID  ;   6   ;   3   ;   10
  UselessV  ; 10  ;   1   ;
  Zipcode ;   12  ;   5   ;   15
 
  So the new datafile should look like this:
 
  PRJ01001   00100END
  PRJ01002   00110END
 
 
 How flexible is the def.csv format?  The difficulty I see with 
 your def.csv format is that it leaves undefined gaps (presumably 
 to be filled in with spaces) and that you also have a blank new 
 place in new file value.  If instead, you could specify the 
 width to which you want to pad it and omit variables you don't 
 want in the output, ordering the variables in the same order you 
 want them in the output:
 
   Variable; Start; Size; Width
   ProjID; 1; 5; 10
   CaseID; 6; 3; 10
   Zipcode; 12; 5; 5
   End; 16; 3; 3
 
 (note that I lazily use the same method to copy the END from the 
 source to the destination, rather than coding specially for it) 
 you could do something like this (untested)
 
import csv
f = file('def.csv', 'rb')
f.next() # discard the header row
r = csv.reader(f, delimiter=';')
fields = [
  (varname, slice(int(start), int(start)+int(size)), width)
  for varname, start, size, width
  in r
  ]
f.close()
out = file('out.txt', 'w')
try:
  for row in file('data.txt'):
for varname, slc, width in fields:
  out.write(row[slc].ljust(width))
out.write('\n')
finally:
  out.close()
 
 Hope that's fairly easy to follow and makes sense.  There might 
 be some fence-posting errors (particularly your use of 1 as the 
 initial offset, while python uses 0 as the initial offset for 
 strings)
 
 If you can't modify the def.csv format, then things are a bit 
 more complex and I'd almost be tempted to write a script to try 
 and convert your existing def.csv format into something simpler 
 to process like what I describe.
 
 -tkc
 
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
  -- 
http://mail.python.org/mailman/listinfo/python-list


RE: text file reformatting

2010-10-31 Thread Braden Faulkner

Sorry to clarify, I was having issues getting this to work. I'm relatively new 
to Python. Sorry for the miscommunication.

 Date: Sun, 31 Oct 2010 16:13:42 -0500
 From: python.l...@tim.thechases.com
 To: brad...@hotmail.com
 CC: python-list@python.org
 Subject: Re: text file reformatting
 
 On 10/31/10 14:52, Braden Faulkner wrote:
  import csv
  f = file('def.csv', 'rb')
  f.next() # discard the header row
  r = csv.reader(f, delimiter=';')
  fields = [
(varname, slice(int(start), int(start)+int(size)), width)
for varname, start, size, width
in r
]
  f.close()
  out = file('out.txt', 'w')
  try:
for row in file('data.txt'):
  for varname, slc, width in fields:
out.write(row[slc].ljust(width))
  out.write('\n')
  finally:
out.close()
 
  I also am having issues with this.
 
 [top-posting fixed -- it's generally frowned upon in this 
 newsgroup/mailing-list and adherence to the preferences will tend 
 to get you a wider audience]
 
 Are your issues with my code, or with the topic at hand?  If it's 
 my code, note my comment about it being untested.  If it's the 
 topic at hand, I recommend trying my code (or a variation 
 there-of after you've tested it).
 
 -tkc
 
 
  -- 
http://mail.python.org/mailman/listinfo/python-list


[Beginer Question] I heard about python needing some sort of _VariableName_ boiler plate?

2010-10-31 Thread Braden Faulkner

Can anyone explain to me how this works, I don't seem to have to do it in IDLE?
Thanks!   -- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python 2.7 or 3.1

2010-10-29 Thread Braden Faulkner

I personally would take only one bite at a time. Meaning only do one then do 
the other later. 
But to each it own :)

 Date: Fri, 29 Oct 2010 17:48:11 -0500
 To: python-list@python.org
 From: jbiq...@icsmx.com
 Subject: Re: Python 2.7 or 3.1
 
 Hello all
 
 Would you consider a not so intelligent move for a newsbie to 
 Python to have maybe version 2.7 and 3.x (if that's possible to be 
 running together on the same machine) to have them run and be 
 learning mainly in 2.7 and see differences in 3.x? In my case I am 
 interested mainly in web applications with a database and if possible 
 being accesing dbase since a projects still runs a big system under 
 dbase format,  or definitely stay with 2.7 for a while until most in 
 migrate it t o 3.x?
 
 Thanks in advance
 Jorge Biquez
 
 At 05:21 p.m. 29/10/2010, geremy condra wrote:
 On Wed, Oct 27, 2010 at 7:18 PM, Braden Faulkner brad...@hotmail.com wrote:
   Would it be safe to say that 2.6 would be even better for beginners than?
 
 Let me just come out with a contrary point of view before you go down
 that path. If you're seriously considering using sqlite, then you may
 be just as well off using Python3 as 2.7 or 2.6- it's in all of the
 above, and Python3 is a big cleanup over previous versions of the
 language.
 
 Geremy Condra
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
  -- 
http://mail.python.org/mailman/listinfo/python-list


Create a GUI and EXE for a python app?

2010-10-28 Thread Braden Faulkner

Having trouble with my mail client, so sorry if this goes through more than 
once. 
I'm worknig on a simple math program as my first application. I would like to 
make a cross-platform pretty GUI for it and also package it up in a EXE for 
distribution on Windows.
What are the best and easiest ways I can do this?Thanks!
  -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 or 3.1

2010-10-27 Thread Braden Faulkner

Would it be safe to say that 2.6 would be even better for beginners than?   
  -- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.7 or 3.1

2010-10-26 Thread Braden Faulkner

Which is better for a beginner to get started in Python with?
Thanks!   -- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydoc enforcement.

2008-12-01 Thread Ken Faulkner
Hi

Yeah, I was thinking about something at commit time for a VCS...   catch is,
soo many VCS's out there.
And I wasn't thinking of the default action throwing compile errors, but
would only do that if a particular flag was given.
Still, just an idea.

I'm just finding more and more public modules/API's/libraries that have so
little documentation that it really does force reading a LOT of the source
to figure out whats going on. Sure, a lot of the time thats required, but
some modules are just painful..

oh well... was just a thought.

Ken



On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer [EMAIL PROTECTED] wrote:


 On Sun, 2008-11-30 at 16:27 -0800, [EMAIL PROTECTED] wrote:
  I've been thinking about implementing (although no idea yet *HOW*) the
  following features/extension for the python compile stage and would be
  interested in any thoughts/comments/flames etc.
 
  Basically I'm interested adding a check to see if:
1) pydoc's are written for every function/method.
2) There are entries for each parameter, defined by some
  predetermined syntax.
 
  My idea is that as much as I love dynamic typing, there are times when
  using some modules/API's that have less than stellar documentation. I
  was thinking that if it was possible to enable some switch that
  basically forced compilation to fail if certain documentation criteria
  weren't met.
 
  Yes, it should be up to developers to provide documentation in the
  first place. Or, the client developer might need to read the source
  (IF its available)...  but having some forced documentation might at
  least ease the problem a little.
 
  For example (half borrowing from Javadoc).
 
  class Foo( object ):
 
def bar( self, ui ):
   pass
 
 
  Would fail, since the bar method has an unknown parameter called
  ui.
  What I think could be interesting is that the compiler forces some
  documentation such as:
 
  class Foo( object ):
 
def bar( self, ui ):
  
  @Param: ui :  blah blah blah.
  
   pass
 
 
  The compiler could check for @Param matching each parameter passed to
  the method/function. Sure, a lot of people might just not put a
  description in, so we'd be no better off. But at least its getting
  them *that* far, maybe it would encourage them to actually fill in
  details.
 
  Now ofcourse, in statically  typed language, they might have the
  description as Instance of UIClass or something like that. For
  Python, maybe just a description of Instance of abstract class UI or
  List of Dictionaries...  or whatever. Sure, precise class names
  mightn't be mentioned (since we mightn't know what is being used
  then), but having *some* description would certainly be helpful (I
  feel).
 
  Even if no-one else is interested in this feature, I think it could
  help my own development (and would be an interested first change
  into Python itself).
 
  Apart from bagging the idea, does anyone have a suggestion on where in
  the Python source I would start for implementing such an idea?
 
  Thanks
 
  Ken

 For the reasons already stated, I think it's probably a bad idea to
 enforce this at compile time.  I think it's a great idea to make sure
 that this information is present in all your code, but unless you want
 to see useless stubs, the correct time to enforce this is at commit
 time.  Don't accept any improperly documented patches.

 Syntax is not enough to ensure what you want to ensure.  The semantics
 have to be right as well.

 Cheers,
 Cliff





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


Re: How can I programmatically find the name of a method from within that method?

2007-08-08 Thread faulkner
On Aug 8, 12:45 am, kj7ny [EMAIL PROTECTED] wrote:
 Is there a way that I can programmatically find the name of a method I
 have created from within that method?  I would like to be able to log
 a message from within that method (def) and I would like to include
 the name of the method from which it was written without having to
 hard-code that value in every message string.  While we're at it, is
 there a way to programmatically get the name of the class and the
 module while I'm at it?

 Thanks,

def foo():
print sys._getframe(0).f_code.co_name

most of the darkest magic of python is in the frames returned by
sys._getframe.

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


Re: How can I programmatically find the name of a method from within that method?

2007-08-08 Thread faulkner
On Aug 8, 10:43 pm, faulkner [EMAIL PROTECTED] wrote:
 On Aug 8, 12:45 am, kj7ny [EMAIL PROTECTED] wrote:

  Is there a way that I can programmatically find the name of a method I
  have created from within that method?  I would like to be able to log
  a message from within that method (def) and I would like to include
  the name of the method from which it was written without having to
  hard-code that value in every message string.  While we're at it, is
  there a way to programmatically get the name of the class and the
  module while I'm at it?

  Thanks,

 def foo():
 print sys._getframe(0).f_code.co_name

 most of the darkest magic of python is in the frames returned by
 sys._getframe.

sorry for the double-post. i forgot to answer the rest of the
question.

class a:
def b(self, *a):
print sys._getframe(0).f_code.co_name
print self.__class__.__name__
print getattr(self,
sys._getframe(0).f_code.co_name).im_class.__name__
print self.__class__.__module__

def log(f):
def newf(*a, **kw):
if a and f.func_code.co_varnames[0] == 'self': print '%s.%s.%s
%r %r' % (a[0].__class__.__module__, a[0].__class__.__name__,
f.func_name, a, kw)
else: print '%s.%s %r %r' % (f.func_globals['__name__'],
f.func_name, a, kw)
f(*a, **kw)
newf.__name__ = f.__name__
newf.__doc__ = f.__doc__
return newf

you can find more interesting attributes of frame and function objects
using the builtin dir function.

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


Re: Heterogeneous lists

2007-08-07 Thread faulkner
On Aug 7, 2:53 pm, Gordon Airporte [EMAIL PROTECTED] wrote:
 This is one of those nice, permissive Python features but I was
 wondering how often people actually use lists holding several different
 types of objects.
 It looks like whenever I need to group different objects I create a
 class, if only so I can use more meaningful names than '[2]' for the items.
 How often do these show up in your code?
 Is this simply the upshot of the underlying arrays holding only object
 references of some sort?

how else would you implement an n-ary tree? eg, AST, CST, minimax, GP.

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


Re: custom plugin architecture: how to see parent namespace?

2007-07-22 Thread faulkner
On Jul 22, 10:06 am, escalation746 [EMAIL PROTECTED] wrote:
 I've got a namespace query that amounts to this: How can an imported
 function see data in the parent custom namespace? I have read through
 numerous posts which skirt this issue without answering it.

 To illustrate, create plugin.py with a couple of functions. The second
 will obviously fail.

 
 def Hello():
 print 'hello'

 def ViewValuable():
 print VALUABLE
 

 Then create master.py which loads the plugin at runtime, later running
 various code fragments against it.

 
 # location of plugin module
 filespec = '/path/to/plugins/plugin.py'
 filepath, filename = os.path.split(filespec)
 filename = os.path.splitext(filename)[0]

 # add to system path
 if filepath not in sys.path:
 sys.path.append(filepath)

 # import into our namespace
 space = __import__(filename, globals(), locals(), [])
 namespace = space.__dict__

 # sometime later in the code... define a new function
 def _plus():
 print 'plus'

 # add that to our namespace
 namespace.update({'Plus': _plus, 'VALUABLE': 'gold'})

 # run custom code
 code = 
 Hello()
 Plus()
 Valuable()
 
 exec code in namespace
 

 This code will echo the lines:
 hello
 plus

 Followed by a traceback for:
 NameError: global name 'VALUABLE' is not defined

 The question is: How do I get a function in plugin.py to see VALUABLE?
 Using external storage of some sort is not viable since many different
 instances of plugin.py, all with different values of VALUABLE, might
 be running at once. (In fact VALUABLE is to be a key into a whole
 whack of data stored in a separate module space.)

 Extensive modifications to plugin.py is also not a viable approach,
 since that module will be created by users. Rather, I need to be able
 to pass something at execution time to make this happen. Or create an
 access function along the lines of _plus() that I can inject into the
 namespace.

 Any help, please? I've been losing sleep over this one.

 -- robin

sys._getframe(1).f_locals

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


Re: bash-style pipes in python?

2007-07-11 Thread faulkner
On Jul 11, 8:56 pm, Dan Stromberg - Datallegro
[EMAIL PROTECTED] wrote:
 I'm constantly flipping back and forth between bash and python.

 Sometimes, I'll start a program in one, and end up recoding in the
 other, or including a bunch of python inside my bash scripts, or snippets
 of bash in my python.

 But what if python had more of the power of bash-style pipes?  I might not
 need to flip back and forth so much.  I could code almost entirely in python.

 The kind of thing I do over and over in bash looks like:

 #!/usr/bin/env bash

 # exit on errors, like python. Exit on undefind variables, like 
 python.
 set -eu

 # give the true/false value of the last false command in a pipeline
 # not the true/false value of the lat command in the pipeline - like
 # nothing I've seen
 set -o pipefail

 # save output in output, but only echo it to the screen if the 
 command fails
 if ! output=$(foo | bar 21)
 then
 echo $0: foo | bar failed 12
 echo $output 12
 exit 1
 fi

 Sometimes I use $PIPESTATUS too, but not that much.

 I'm aware that python has a variety of pipe handling support in its
 standard library.

 But is there a similarly-simple way already, in python, of hooking the stdout 
 of
 process foo to the stdin of process bar, saving the stdout and errors from 
 both
 in a variable, and still having convenient access to process exit values?

 Would it be possible to overload | (pipe) in python to have the same behavior 
 as in
 bash?

 I could deal with slightly more cumbersome syntax, like:

 (stdout, stderrs, exit_status) = proc('foo') | proc('bar')

 ...if the basic semantics were there.

 How about it?  Has someone already done this?

class P(subprocess.Popen):
def __or__(self, otherp):
otherp.stdin.write(self.stdout.read())
otherp.stdin.close()
return otherp
def __init__(self, cmd, *a, **kw):
for s in ['out', 'in', 'err']: kw.setdefault('std' + s, -1)
subprocess.Popen.__init__(self, cmd.split(), *a, **kw)

print (P('cat /etc/fstab') | P('grep x')).stdout.read()

of course, you don't need to overload __init__ at all, and you can
return otherp.stdout.read() instead of otherp, and you can make
__gt__, __lt__ read and write files. unfortunately, you can't really
fudge , , |, or any of the more useful pipes, but you can make
more extensive use of __or__:

class Pipe:
def __or__(self, other):
if isinstance(other, Pipe): return ...
elif isinstance(other, P): return ...
def __init__(self, pipe_type): ...

k = Pipe(foo)
m = Pipe(bar)

P() |k| P()
P() |m| P()

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


Re: Get a filename list of a web site

2007-07-10 Thread faulkner
On Jul 10, 5:12 am, [EMAIL PROTECTED] wrote:
 Hi all,
 is it possible to get a filename directory list of a website (possibly
 with full path indication)?
 Using python  possibly wget?

 Bye.

HTTP does not provide a command for this.
you need to acquire a shell account on the specific server you're
interested in. generally, this requires emailing the addresses in the
whois database, explaining why you need a shell account. generally,
they will deny your request.
then you can say `ssh [EMAIL PROTECTED] ls DIRECTORY`.
a few directories on a few servers are configured such that they list
themselves when queried. iirc, there's a google trick to let you find
these directories.

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


Re: Too many 'self' in python.That's a big flaw in this language.

2007-06-27 Thread faulkner
On Jun 27, 7:02 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 HI
 I'm currently using Python. I find that a instance variable must
 confined with self,
 for example:
 class a:
 def __init__(self):
 self.aa=10
 def bb(self):
 print self.aa # See .if in c++,I could use aa to change that
 variable

 That's a big inconvenience in coding ,especially when you have lot of
 variable
 If you method need 10 variables ,you have to type self for 10 times
 and that also makes your variable longer.

 From My point,I think this only help python interpreter to deside

 where to look for.
 Is there anyone know's how to make the interpreter find instance name
 space first?
 Or any way to make programmer's life easier?

http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e584

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


Re: labeled break/continue

2007-06-18 Thread faulkner
On Jun 18, 12:35 am, Matt Chisholm [EMAIL PROTECTED] wrote:
 Hi.  I was wondering if there had ever been an official decision on
 the idea of adding labeled break and continue functionality to Python.

 I've found a few places where the idea has come up, in the context of
 named code blocks:

 http://groups.google.com/group/comp.lang.python/browse_thread/thread/...

 and in the context of discussing do/while loops and assignments in
 conditionals:

 http://groups.google.com/group/comp.lang.python/browse_thread/thread/...

 Both of those discussions just kind of petered out or changed
 direction without any conclusion.

 There's also this Python 2.6 which has a similar syntax (although
 different semantics) to one of the syntaxes proposed in the first
 discussion above:

 http://sourceforge.net/tracker/index.php?func=detailaid=1714448grou...

 I would be willing to help make a case and then write a PEP for
 labeled break and continue, as long as the community or the BDFL
 hasn't already decided against it.

 -matt

 P.S. My apologies about cross posting; python-ideas seems like a
 better place to post this, but PEP 1 says to post to python-list.

python-dev just mentioned that the BDFL vetoed it a while ago.
they're writing a PEP just to document why it was vetoed.

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


Re: getting scancodes

2007-04-25 Thread faulkner
On Apr 23, 8:39 pm, [EMAIL PROTECTED] wrote:
 Anyone knows if its possible to get scan codes ???
 I tried with getch () but with no success, just keycodes.
 May be using the something in the sys.stdin module ??

is this what you're looking for?
http://cheeseshop.python.org/pypi/sysio/1.0

and sys.stdin isn't a module. it's a file.

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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-14 Thread faulkner
On Apr 14, 6:27 am, [EMAIL PROTECTED] wrote:
 This is like the previous one. Please check for sanity and approve for
 posting at python-dev.

 I would like to have something like option base in Visual Basic.
 IIRC it used to allow me to choose whether 0 or 1 should be used as
 the base of member indices of arrays. In Python, the same can be used
 with strings, lists, tuples etc.

 This would mean:
 foo = foo
 = foo[1] == 'f'

 foo = ['foo', 'bar', 'spam' ]
 = foo[1] == 'foo'

 foo = ('spam', 'eggs')
 = foo[1] == 'spam'

 For convenience it should also affect the range function so that:

 range(3) = [1, 2, 3]

 because this is often used where arrays would be used in VB.

 Finally, when the programmer does not specify his choice of base at
 the beginning of the program, the current behaviour of using 0 as base
 should continue so that there is no problem with backward
 compatibility.

__future__ is used to access upcoming features, and changing the base
offset is not [and never will be] slated for future development. zero
has been used as the base offset in all real languages since the dawn
of time, and isn't something that can be changed without seriously
breaking heads.

i can't believe nobody's posted this yet:
http://www.xkcd.com/c163.html

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


Re: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place

2007-04-14 Thread faulkner
On Apr 14, 6:30 am, [EMAIL PROTECTED] wrote:
 Please check for sanity and approve for posting at python-dev.

 Currently file-directory-related functionality in the Python standard
 library is scattered among various modules such as shutil, os,
 dircache etc. So I request that the functions be gathered and
 consolidated at one place. Some may need renaming to avoid conflicts
 or for clarification.

checkout the py3k svn branch and submit a patch [extending or
conforming to pep355] to python-dev.

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


Re: tkinter how to write

2007-03-07 Thread faulkner
On Mar 8, 7:07 pm, Gigs_ [EMAIL PROTECTED] wrote:
 as I write my first gui program (text editor) I wanna ask you guys how
 to separate code in classes.?
 Should I put in one class my menu and in another class text and
 scorllbars etc?

 or something else?

 thanks


Use the force. Do whatever feels most right. Remember that you can
always refactor.
A good rule of thumb for GUIs is MVC [a class or set of classes to
encapsulate the abstract relationships known as the Model, another
class or set of classes to handle translating changes to the model
into changes in the GUI aka View, and another class or set of classes
to encapsulate the Controlling of everything], but do not pursue this
to its extreme inanity as Java does. Follow guidelines only so long as
they clarify the code. The second you can no longer keep the overall
structure of the code in your head at once, hit control+z until you
can.

When I wrote my text editor, I wanted to keep everything in one class
because I thought it would be cleaner. Several thousand lines later, I
realized that the notion of a Tab is a significant and powerful
abstraction, as is the UndoStack and the entries in it [UndoEntry].
Right now, I'm thinking about separating all the menuitem callbacks
into their own class because they are different in kind from the
methods which encapsulate the Tabs, menubar, statusbar, etc. into an
application. The reason that I probably won't do this is that a class
is not for grouping methods, it's for representing objects.

UML is another expounded tool for achieving OOP zen before you set
fingertips to keyboard. i've never grokked it, but you should try it
at least once, if only so you can say that you have in a job interview.

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


Re: builtin set literal

2007-02-14 Thread faulkner
On Feb 14, 11:55 am, Schüle Daniel [EMAIL PROTECTED] wrote:
 Hello,

 lst = list((1,2,3))
 lst = [1,2,3]

 t = tupel((1,2,3))
 t = (1,2,3)

 s = set((1,2,3))
 s = ...

 it would be nice feature to have builtin literal for set type
 maybe in P3 .. what about?
 s = 1,2,3

 Regards, Daniel

sets aren't quite that useful or common. just use a list.
and '' and '' already have syntactic meanings.
and that would make python look more like C++, which nobody wants.

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


Re: Something like the getattr() trick.

2007-02-10 Thread faulkner
On Feb 10, 3:34 pm, Ayaz Ahmed Khan [EMAIL PROTECTED] wrote:
 I'm working with the following class heirarchy (I've snipped out the code
 from the classes):

 class Vuln:
 def __init__(self, url):
 pass

 def _parse(self):
 pass

 def get_link(self):
 pass

 class VulnInfo(Vuln):
 pass

 class VulnDiscuss(Vuln):
 pass

 def main(url):
 vuln_class = ['Info', 'Discuss']
 vuln = Vuln(url)
 vuln._parse()
 for link in vuln.get_link():
 i = VulnInfo(link)
 i._parse()
 d = VulnDiscuss(link)
 d._parse()

 Is there a way to get references to VulnInfo and VulnDiscuss objects using
 something like the getattr trick? For example, something like:

 for _class in vuln_class:
 class_obj = getattr('Vuln%s' % (_class,) ..)
 a = class_obj(link)
 a._parse()

 getattr() takes an object as its first argument. I can't seem to figure
 out how to make it work here.

 --
 Ayaz Ahmed Khan

 A witty saying proves nothing, but saying something pointless gets
 people's attention.

eval('Vuln' + _class)
or,
Vuln.Discuss = VulnDiscuss
getattr(Vuln, _class)

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


Lython

2007-01-25 Thread faulkner
I have Lython!
I want to make sure that anybody else who wants it can access it, so,
unless Mr. Egan objects, I'm hosting it here:
http://home.comcast.net/~faulkner612/programming/python/lython.zip
I had to patch it a bit because the number of arguments to
compiler.ast.Function.__init__ changed between 2.3 and 2.4, when
decorators were introduced. I haven't tested it on 2.5 because the last
time I upgraded python, my gentoo died.
I also took the liberty of adding some features such as primitive
interactivity, a '-c code' option, a '-h' option, an rc file
'~/.lythonrc.ly', and a '-o file' option which dumps bytecode to file.
I've slated developing support for *args, **kwargs, default arguments,
+= and -= etc., reader macros ala common lisp, classes,
try...except...finally, and raise.

For the curious, here are some other implementations of lisp in python:
http://ibiblio.org/obp/py4fun/lisp/lisp.html
http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/
http://www.xs4all.nl/~yduppen/site/psyche.html
http://www.biostat.wisc.edu/~annis/creations/PyLisp/

These implementations are great, but Lython has macro capabilities,
generates python byte code, and demonstrates the use of spark, a
fantastic parsing package.

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


Re: question on pygtk and accessibility on windows.

2006-11-30 Thread faulkner
if by 'accessibility' you mean 'usable' (like python and firefox are
usable), then yes. there are pygtk bindings for windows, and they work.
http://python-forum.org/py/viewtopic.php?t=116
if by 'accessibility' you mean 'usable for the blind/deaf', then i
think that is up to you as an application developer.

krishnakant Mane wrote:
 has any one tried py gtk on windows?
 I tried to do a google search for accessibility related issues but did
 not find any thing specific to pygtk and windows accessibility.
 I even tried to search for just gtk and windows accessibility but
 again no result.
 so I am now posting this message as a last hope to at least get a yes
  or no  answer on whether py gtk is accessible with windows.
 thanks.
 Krishnakant.

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


Re: why would anyone use python when java is there?

2006-11-28 Thread faulkner
functional programming, list comprehensions, decorators, duck typing,
generators, dynamism, introspection, prettier code, simpler grammar
[see digg and /. for the graphs], and, of course, the trolls.

gavino wrote:
 wtf

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


Re: Simple question to split

2006-11-09 Thread faulkner
def splits(seq, cs):
if not cs: return seq
elif isinstance(seq, str): return splits(seq.split(cs[0]), cs[1:])
else: return splits(sum([elem.split(cs[0]) for elem in seq], []),
cs[1:])

or
a = re.split('(\ |\,)', a)
a.remove(' ')
a.remove(',')

Matthias Winterland wrote:
 Hi,

 I have a simple question. When I read in a string like:
 a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a
 single split-call?
 
 Thx,
 Matthias

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


Re: Computer locks up when running valid stand alone Tkinter file.

2006-10-25 Thread faulkner
 But, when I call it from another module it locks
methinks this other module has the answer.

jim-on-linux wrote:
 py help,

 The file below will run as a stand alone file.
 It works fine as it is.

 But, when I call it from another module it locks
 my computer, The off switch is the only
 salvation.

 This module when run as a stand alone, it will
 open a jpeg image and add a vertical and
 horizontal scrollbar to the canvass.
 That's all it does.

 Replace the img9.jpg file with one of your own,
 put the image in the current working dir., and
 run.

 If you think you can help, I would appreciate it.


 jim-on-linux





 

 #!/usr/bin/env python

 
 #
 import Tkinter as Tk

 Do not do
 ( from Tkinter import * )
 because of  name space conflict with
 Image.open

 ##

 below imports  Image and ImageTk are from
 Imaging-1.1.5, PIL  in Python

 


 import Image
 import  ImageTk
 import Tkinter as Tk
 import os

 vpath = os.getcwd()+os.sep+'img9.jpg'



 class Kshow_0 :

 def __init__(self ) :
 self.Fimgshow0()

 def Fimgshow0(self ) :
 window = Tk.Tk()# used for stamd alone

#  window = Tk.Toplevel()
  # Above Toplevel call used when running
   # from another file



 window.title(' Image Location '+vpath )
 window.protocol('WM_DELETE_WINDOW',
window.destroy)

 vcanvas = Tk.Canvas(window, width = 375,
height=375,
   borderwidth = 1, bg=
'white')

 sbarY=Tk.Scrollbar()
 sbarX = Tk.Scrollbar( orient='horizontal')
 sbarY.config(command= vcanvas.yview)
 sbarX.config(command= vcanvas.xview)

 vcanvas.config(yscrollcommand=sbarY.set)
 vcanvas.config(xscrollcommand=sbarX.set)

 sbarY.pack(side='right', fill='y')
 sbarX.pack(side='bottom', fill='x')
 vcanvas.pack(expand='yes',  fill='both')

 im= Image.open( vpath)
 tkim = ImageTk.PhotoImage(im)

 imgW = tkim.width()
 print imgW, '## imgW, jpg 58\n'

 imgH = tkim.height()
 print imgH, '## imgH, jpg 61\n'

 # Draw the image on the canvas
 vcanvas.create_image(0, 0,  image=tkim,
 anchor = 'nw'  )

 vcanvas.config(scrollregion= (0, 0, imgW,
imgH))
 window.mainloop ()
 
 
 if __name__ == '__main__' :
 
 Kshow_0()

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


Re: Painless way to do 3D visualization

2006-10-07 Thread faulkner
http://www.vpython.org/

Peter Beattie wrote:
 Hey folks,

 I need to do the following relatively simple 3D programming:

 I want to convert data from four-item tuples into 3D co-ordinates in a
 regular tetrahedron. Co-ordinates come in sequences of 10 to 20, and the
 individual dots in the tetrahedron need to be connected into
 discontinuous lines. A single tetrahedron should contain at least two,
 possibly more, such lines. I would like to show certain similarities in
 the sequences/lines, eg by changing color, thickness, or maybe attaching
 indeces to certain points in a particular sequence.

 I'd welcome suggestions as to what might be the most painless way to
 achieve this in Python. So far, I've only tinkered a little with
 VPython, but the lack of any decent documentation has proved to be a
 major turn-off.
 
 TIA!
 
 -- 
 Peter

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


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread faulkner
__int__
__long__
__float__


Matthew Wilson wrote:
 What are the internal methods that I need to define on any class so that
 this code can work?

 c = C(three)

 i = int(c) # i is 3

 I can handle the part of mapping three to 3, but I don't know what
 internal method is called when int(c) happens.

 For string conversion, I just define the __str__ method.  What's the
 equivalent for int?  For float, too, while I'm at it?

 TIA

 Matt

 --
 A better way of running series of SAS programs:
 http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles

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


Re: python gtk based file manager

2006-09-25 Thread faulkner
http://www.google.com/search?q=emelfm2
awesome file manager written in C using gtk.
i've been meaning to write something like emelfm in pygtk, but emelfm
already exists...

Fabian Braennstroem wrote:
 Hi,

 I am looking for a file manager based on pygtk. It seems
 that there does not exist any!? Maybe, someone has a hint or
 already some starting code lines for such a 'thing'!?
 
 Greetings!
  Fabian

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


Re: does anybody earn a living programming in python?

2006-09-25 Thread faulkner
both my last summer jobs consisted entirely of python, and the jobs i'm
looking at for next summer all involve python. and one of my profs
makes a living teaching python. and the office i worked for 2 summers
ago was 5 old guys who did nothing but python and stock trade analysis
all day.
if i'm lucky, my career employer after i get out of grad school will
let me play with python and lisp all day everyday.
[so, google, please don't start sucking any time soon.]


walterbyrd wrote:
 If so, I doubt there are many. 
 
 I wonder why that is?

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


Re: does anybody earn a living programming in python?

2006-09-25 Thread faulkner
where do you find these contract jobs, if you don't mind my asking?

Christian wrote:
 walterbyrd wrote:
  If so, I doubt there are many.
 
  I wonder why that is?

 Previously I used Python while earning a living working in IT at a
 college.  Currently it is putting food on the table via contract jobs.
 I imagine there are many out there like me, doing just that.
 
 Christian
 http://www.dowski.com

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


Re: Best practice for large source code projects

2006-09-22 Thread faulkner
several of my programs are thousands of lines long, and i don't think
they're extravagantly large.
i'd say you should use modules the same way you use classes and
functions: to separate code logically.
if it makes sense to think of a group of statements as a function, you
make it a function. if it makes sense to think of a group of functions
as data as a single object, you make a class. if it makes sense to
think of a collection of classes and functions and data as a collective
unit, make a module. and so on for packages.
if it makes sense for a single function to be hundreds or thousands of
lines long, so be it.
follow the modern poet's rule: ignore restrictions that don't make
sense, and follow closely the restrictions you choose.


[EMAIL PROTECTED] wrote:
 I'm developing a web system and based on some patterns I've seen
 elsewhere, I made a single  file (model.py) to hold all of the
 functions and classes that define the model porition of the
 application. Hence the code in the controller looks like:

 import model

 def Display(req,id):
   # 


 It works and things make sense to me. Yet, I feel uneasy that my
 model.py file is starting to approach 500 lines. What's the best
 practice or community opinion on this? Do I keep everything in a single
 file or do I start dividing things into separate files?
 
 TIA

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


Re: How to find number of characters in a unicode string?

2006-09-18 Thread faulkner
are you sure you're using unicode objects?
len(u'\u') == 1
the encodings module should help you turn '\xff\xff' into u'\u'.

Preben Randhol wrote:
 Hi

 If I use len() on a string containing unicode letters I get the number
 of bytes the string uses. This means that len() can report size 6 when
 the unicode string only contains 3 characters (that one would write by
 hand or see on the screen). Is there a way to calculate in characters
 and not in bytes to represent the characters.

 The reason for asking is that PyGTK needs number of characters to set
 the width of Entry widgets to a certain length, and it expects viewable
 characters and not number of bytes to represent them.
 
 
 Thanks in advance
 
 
 Preben

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


Re: Webbrowser written totally in Python

2006-09-17 Thread faulkner
this was just on digg:
##
import wx
from urllib import urlopen
import wx.html

class Frame(wx.Frame):

def userPageButton(self, event):
goToPage=self.userPage.GetValue()
goToPage='http://www.' + goToPage
webpage=urlopen(goToPage).read()
displayPage=self.html.SetPage(webpage)

def __init__(self):
wx.Frame.__init__(self, parent=None, id=-1, 
title='microBrowser',
size=(800, 600), pos=(50, 50))
panel=wx.Panel(self)
self.userPage=wx.TextCtrl(panel, pos=(400, 5)) #
self.html = wx.html.HtmlWindow(panel, id=-1, size=(780, 530),
pos=(10, 35), style=wx.html.HW_SCROLLBAR_AUTO)
userPageButton=wx.Button(panel, label='Go!', pos=(300, 5))
userPageButton.Bind(wx.EVT_BUTTON, self.userPageButton)

class App(wx.App):

def OnInit(self):
self.frame=Frame()
self.frame.Show()
self.SetTopWindow(self.frame)
return True

if __name__=='__main__':
app=App()
app.MainLoop()

#
there are also python bindings for gtkmozembed in gnome-python-extras
and here:
http://sourceforge.net/projects/pygtkmoz


Franz Steinhaeusler wrote:
 Hello NG,

 is there any (GUI) webbrowser written completly in Python?
 
 in pyGtk, pyQt, wxPython or TkInter?
 
 -- 
 Franz Steinhaeusler

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


Re: Cross-platform application restart?

2006-09-06 Thread faulkner
asynchronously start a process which waits for the parent to close,
then starts your script.

cmd = python -c 'import time,os;time.sleep(2);os.system(YOUR_SCRIPT)'
if os.name == 'nt':
cmd = 'start ' + cmd
else:
cmd += ' '
subprocess.Popen(cmd, shell=True)
sys.exit()

Heikki Toivonen wrote:
 Is there any way to restart a Python (GUI) application that would work
 on Windows, Mac OS X and Linux? I'd like to provide a restart button
 to a dialog that would restart the application to pick new changes or
 start with different options.
 
 -- 
   Heikki Toivonen

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


Re: looking for data on csv files

2006-08-28 Thread faulkner
import re
if re.search(nome, row[rowcsv], re.I):
...

that's re.I [capital i] as in ignorecase.

flit wrote:
 Hi!
 I am using the csv modules..

 when I use the command:

 if nome in row[rowcsv]:
 print \n
 print row[rowcsv] + \n  + row[11] + \n
 print
 

 there is this case:

 1- data on file PUItarr

 If the user try to find for puitarr or PUITARR it doesn´t find.

 I tried the string.upper and .lower , but there is a a way to look far
 all possible combinations?
 
 And yes, i am a newbie..

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


Re: Python daemon process

2006-08-26 Thread faulkner
process = subprocess.Popen(gnuchess)
...
os.kill(process.pid, signal.SIGKILL)

Thomas Dybdahl Ahle wrote:
 Hi, I'm writing a program, using popen4(gnuchess),
 The problem is, that gnuchess keeps running after program exit.

 I know about the atexit module, but in java, you could make a process a
 daemon process, and it would only run as long as the real processes ran. I
 think this is a better way to stop gnuchess, as you are 100% sure, that
 it'll stop.
 
 Can you do this with popen?
 
 -- 
 Thomas

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


Re: Newbie programmer question: How do parsers work?(Python examples?)

2006-08-25 Thread faulkner
http://pages.cpsc.ucalgary.ca/~aycock/spark/
http://www-128.ibm.com/developerworks/library/l-spark.html

bio_enthusiast wrote:
 I was wondering exactly how you create a parser. I'm learning
 Python and I recently have come across this material. I'm interested
 in the method or art of writing a parser.

 If anyone has some python code to post for an abstract parser, or links
 to some informative tutorials, that would be great.

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


Re: callable to disappear?

2006-08-23 Thread faulkner
what's wrong with hasattr(obj, '__call__')?

Antoon Pardon wrote:
 I have been reading http://www.python.org/dev/peps/pep-3100/
 en there is written:

   To be removed:
  ...

  callable(): just call the object and catch the exception

  ...

 But that doesn't seem to be a generally available option.
 The place where you want to check if something is callable
 doens't need to be the place where you actually want to call
 it. Removing callable will mean that you can't check whether
 or not something is callable without incurring the side-effects
 of calling it.

 I also think code will become more ugly

 How do you suggest I would code the following:

 if callable(func):
 for i, el in lst:
 lst[i] = func(el)
   othercode()


 I can code as follows:

 try:
 for i, el in lst:
   lst[i] = func(el)
   othercode()
 except TypeError:
 pass


 But this has the problem that othercode could throw a TypeError:

 So it seems I would need at least two try statements

 try:
 for i, el in lst:
   try:
   lst[i] = func(el)
   except TypeError
   raise LoopBreak
   othercode()
 except LoopBreak:
 pass

 And this still has problems because the TypeError could be
 raised because lst is an unsubscriptable object.


 Is there a chance this will be reconsidered?
 
 -- 
 Antoon Pardon

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


Re: swapping numeric items in a list

2006-08-22 Thread faulkner
for i in xrange(0, len(your_list), 2):
your_list[i], your_list[i + 1] = your_list[i + 1], your_list[i]


Jiang Nutao wrote:
 Hi,

 I simplify my problem like below

 To convert list
 aa = [0x12, 0x34, 0x56, 0x78]
 into
 [0x34, 0x12, 0x78, 0x56]
 
 How to do it fast? My real list is huge.
 
 Thanks a lot.
 Jason

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


Re: [NEWB]: List with random numbers

2006-08-20 Thread faulkner
what you want is impossible. step back a second. you want 7 distinct
ints all between 0 and 5 inclusive. of course you'll loop forever. once
you get all 6 numbers, no matter what you get will already be in your
list.
if you want floats between 0 and 6, say '6 * random.random()'.
random.randrange is equivalent to random.choice(range(*arguments)),
which only deals with whole numbers.

eltower wrote:
 Hey all,

 I'm trying to write a program in Python for learning purposes which is
 meant to:

 Generate a random number from 0 to 6
 Insert this random number to the end of a list unless the number is
 already there
 finish with a len(list) = 7

 so far, I have this:

 import random

 random_list = []

 while len(random_list)  8:
   j = random.randrange(6)
   if (j in random_list):
   continue
   else:
   random_list.append(j)
   continue

 print random_list


 however, I get stuck in an infinite loop.
 
 Any suggestions? 
 
 Thank you in advance,
 
 Adri

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


Re: TypeError: 'module' object is not callable (newby question)

2006-08-14 Thread faulkner
works for me. do you do anything in your script besides that?


Charles Russell wrote:
 Why does this work from the python prompt, but fail from a script?
 How does one make it work from a script?

 #! /usr/bin/python
 import glob
 # following line works from python prompt; why not in script?
 files=glob.glob('*.py')
 print files

 Traceback (most recent call last):
File ./glob.py, line 2, in ?
  import glob
File /home/cdr/python/glob.py, line 5, in ?
  files=glob.glob('*.py')
 TypeError: 'module' object is not callable

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


Re: seeking the Hello World of Packages

2006-08-11 Thread faulkner
yep, that's all a package is.
if you have trouble importing, check your PYTHONPATH environment
variable, or sys.path.

Bell, Kevin wrote:
 I'm trying to get an idea of how packages work and I've read about it in
 the Py Tutorial and Nutshell, but I'm still craving a concrete example
 that I can poke through.  Does anyone have a really basic package that
 does very little that I could look at?

 What I've gathered thus far is that a package is simply a directory, say
 C:\MyPackage, that would contain __init__.py which tells Python to be
 aware of all the other modules in C:\MyPackage.  Am I correct?

 C:\MyPackage\
 \__init__.py
 \justPrintHelloWorld.py
 \multiply5By10.py

 Would I expect the following behavior?:

 import MyPackage
 MyPackage.justPrintHelloWorld
 Hello World
 MyPackage.multiply5by10
 50

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


Re: Problem reading/writing files

2006-08-03 Thread faulkner
have you been using text mode?

[EMAIL PROTECTED] wrote:
 This is a bit of a peculiar problem. First off, this relates to Python
 Challenge #12, so if you are attempting those and have yet to finish
 #12, as there are potential spoilers here.

 I have five different image files shuffled up in one big binary file.
 In order to view them I have to unshuffle the data, which means
 moving bytes around. Currently my approach is to read the data from the
 original, unshuffle as necessary, and then write to 5 different files
 (2 .jpgs, 2 .pngs and 1 .gif).

 The problem is with the read() method. If I read a byte valued as 0x00
 (in hexadecimal), the read method returns a character with the value
 0x20. When printed as strings, these two values look the same (null and
 space, respectively), but obviously this screws with the data and makes
 the resulting image file unreadable. I can add a simple if statement to
 correct this, which seems to make the .jpgs readable, but the .pngs
 still have errors and the .gif is corrupted, which makes me wonder if
 the read method is not doing this to other bytes as well.

 Now, the *really* peculiar thing is that I made a simple little file
 and used my hex editor to manually change the first byte to 0x00. When
 I read that byte with the read() method, it returned the correct value,
 which boggles me.

 Anyone have any idea what could be going on? Alternatively, is there a
 better way to shift about bytes in a non-text file without using the
 read() method (since returning the byte as a string seems to be what's
 causing the issue)? Thanks in advance!

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


Re: gaierror: (8, 'hostname nor servname provided, or not known')

2006-07-31 Thread faulkner
my boss has a similar problem with his home internet connection in
general. he traced it back to his router, which was in the first couple
generations of routers. how old are the routers you tested this on?
aside from upgrading them, if they are the problem, i can suggest a
workaround.
the first time this exception is raised, your script can automatically
restart itself.
os.system('python -c import time, os; time.sleep(2);
os.system(\'python yourscriptname.py \') ')
sys.exit(1)


Laszlo Nagy wrote:
 Hello,

 I asked this question about a week ago, but I did not provide a
 traceback. Here is the traceback:

   File /usr/local/lib/python2.4/xmlrpclib.py, line 1096, in __call__
 return self.__send(self.__name, args)
   File /usr/local/lib/python2.4/xmlrpclib.py, line 1383, in __request
 verbose=self.__verbose
   File /usr/local/lib/python2.4/xmlrpclib.py, line 1129, in request
 self.send_content(h, request_body)
   File /usr/local/lib/python2.4/xmlrpclib.py, line 1243, in send_content
 connection.endheaders()
   File /usr/local/lib/python2.4/httplib.py, line 798, in endheaders
 self._send_output()
   File /usr/local/lib/python2.4/httplib.py, line 679, in _send_output
 self.send(msg)
   File /usr/local/lib/python2.4/httplib.py, line 646, in send
 self.connect()
   File /usr/local/lib/python2.4/httplib.py, line 1072, in connect
 sock.connect((self.host, self.port))
   File string, line 1, in connect
 gaierror: (8, 'hostname nor servname provided, or not known')

 The program is connecting to the same host about 2 times per minute.
 After running for one or two hours, it raises this exception. Once it
 raised this exception, it keeps raising in. (My program is trying to
 connect but it cannot.) Then I restart my program and it works for
 anoter hour or two. I tried the same program on different machines and
 different operating system, but the error is always the same. Please
 help me identify the problem.
 
 Thanks,
 
Laszlo

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


Re: class variables

2006-07-30 Thread faulkner
python != java.
when you say self.v = ..., you mask the class attribute with an
instance attribute.
say C1.v = 

Colin J. Williams wrote:
 Andre Meyer wrote:
  Hi all
 
  I am trying to understand the magic of Python's class variables and
  tried the following code (see below).
 
  Just out of curiosity, I tried to define a property that provides access
  to a seemingly instancae variable which is in fact a class variable. All
  seems to work fine (case 4), but when a custom object is assigned, an
  instance variable is created instead of using theproerty (case 5).
 
  What goes wrong here? What is the difference between cases 4 and 5? How
  can case 5 be fixed?
 
  thanks a lot for your help
  Andre
 
  Code Listing
  =
 
  print; print *** Case 1 ***; print
 
  class C1(object):
 
  v = None
 
  def __init__(self, value):
  print '-', self.v
  self.v = value
 
  def value(self):
  return self.v
 
  a1 = C1(1)
  b1 = C1(2)
  print a1.value()
 
  print; print *** Case 2 ***; print
 
  class C2(object):
 
  v = None
 
  def __init__(self, value):
  print '-', self.v
  self.__class__.v = value
 
  def value(self):
  return self.__class__.v
 
  a2 = C2(1)
  b2 = C2(2)
  print a2.value()
 
  print; print *** Case 3 ***; print
 
  class C3(object):
 
  v = 5
 
  def __init__(self, value):
  print '-', self.v
  self.v = self.v + value
 
  def value(self):
  return self.v
 
  a3 = C3(1)
  b3 = C3(2)
  print a3.value()
  print a3.v
  print a3.__class__.v
 
  print; print *** Case 4 ***; print
 
  class V4(list):
  def work(self):
  return 'done'
 
  class C4(object):
 
  def __set_v(self, v): self.__class__.__v = v
  def __get_v(self): return self.__class__.__v
  def __del_v(self): del self.__class__.__v
  v = property(__get_v, __set_v, __del_v, 'make class variable')
  v = V4()
 
  def __init__(self, value):
 
  print '-', self.v
  self.v.append(value)
  print '+', self.v
 
  @classmethod
  def value(self):
  print self.v.work()
  return self.v
 
 
  a4 = C4(1)
  b4 = C4(2)
  print a4.value()
  print a4.v
  print a4.__class__.v
  print a4.v.work()
 
 
  print; print *** Case 5 ***; print
 
  class V5(object):
  def __init__(self, i):
  self.i = i
 
  def work(self):
  return 'done', self.i
 
  class C5(object):
 
  def __set_v(self, v): self.__class__.__v = v
  def __get_v(self): return self.__class__.__v
  def __del_v(self): del self.__class__.__v
  v = property(__get_v, __set_v, __del_v, 'make class variable')
  v = None
 
  def __init__(self, value):
 
  print '-', self.v
  self.v = V5(value)
  print '+', self.v
  #print self.__class__.__dict__
  #print self.__dict__
 
  @classmethod
  def value(self):
  print self.v.work()
  return self.v
 
 
  a5 = C5(1)
  b5 = C5(2)
  print a5.value()
  print a5.v
  print a5.__class__.v
  print a5.v.work()
 
 
  Output
  =
 
 
  *** Case 1 ***
 
  - None
  - None
  1
 
  *** Case 2 ***
 
  - None
  - 1
  2
 
  *** Case 3 ***
 
  - 5
  - 5
  6
  6
  5
 
  *** Case 4 ***
 
  - []
  + [1]
  - [1]
  + [1, 2]
  done
  [1, 2]
  [1, 2]
  [1, 2]
  done
 
  *** Case 5 ***
 
  - None
  + __main__.V5 object at 0x00AFE0D0
  - None
  + __main__.V5 object at 0x00AFE110
  Traceback (most recent call last):
File classvariables.py, line 121, in ?
  print a5.value ()
File classvariables.py, line 115, in value
  print self.v.work()
  AttributeError: 'NoneType' object has no attribute 'work'
 
 André,

 I would have expected a5.v to be equal to b5.v, otherwise what is the
 value of a class variable?

 I get:
 [Dbg] a5.v == b5.v
 False
 
 I hope that one of the wizards will respond.
 
 Colin W.

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


Re: Small problem with print and comma

2006-07-30 Thread faulkner
why don't you iterate over the list instead of indices?
for elem in L: print elem,

you don't need the 0 when you call range: range(0, n) == range(n)
the last element of a range is n-1: range(n)[-1] == n-1
you don't need while to iterate backwards. the third argument to range
is step.
range(n-1, -1, -1) == [n-1, n-2, n-3, ..., 1, 0]

[EMAIL PROTECTED] wrote:
 Hi,

 I have a small problem with my function: printList. I use print with a
 ',' . Somehow the last digit of the last number isn't printed. I wonder
 why.

 import random

 def createRandomList(param):
 length = param

 a = []
  creating random list
 for i in range(0,length):
   a.append(random.randrange(100))
 return a

 def printList(param):
 #doesn't work
 #2 sample outputs
 # 30 70 68 6 48 60 29 48 30 38
 #sorted list
 #6 29 30 30 38 48 48 60 68 7  --- last character missing

 #93 8 10 28 94 4 26 41 72 6
 #sorted list
 #4 6 8 10 26 28 41 72 93 9 -- dito


 for i in range(0,len(param)):
   print a[i],
#works
#for i in range(0,len(param)-1):
#  print a[i],
#print a[len(param)-1]


 if __name__ == __main__:
   length = 10
   a = createRandomList(length)
   printList(a)

   for j in range(1,len(a)):
   key = a[j]
   i = j-1
   while i  -1 and a[i]key:
   a[i+1] = a[i]
   i = i-1
   a[i+1] = key
   
   print \n sorted list
   printList(a)

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


Re: War chest for writing web apps in Python?

2006-07-28 Thread faulkner
cygwin
http://www.cygwin.com/
try a few IDEs out to see which fits you best. IDLE ships with python,
and isn't significantly objectively worse than any other python IDE,
afaik.
GUI designers aren't necessary because there's usually so little
boilerplate code in any python toolkit, but, again, whatever works best
for you.
[wait, will you be running a GUI on a webhost?]
if you haven't selected a web framework, may i steer you towards
cherrypy? it stays out of your way more than any other web framework
i've tried. and i'm using it now to build a databased web-app for my
college.
http://www.cherrypy.org/


Vincent Delporte wrote:
 Hello

 I'm thinking of using Python to build the prototype for a business web
 appplication. The development and test machine is XP, while ultimate
 deployment will be on a shared Unix web host.

 What would you recommend I get, besides the Python engine itself? Good
 IDE (Kodomo?) ? Some kind of GUI designer? Add-on's? Other tools?
 
 Thank you.

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


Re: list of lists of lists ....

2006-07-28 Thread faulkner
recursion.
def get_As(L):
res = []
for elem in L:
if isinstance(elem, A):
res.append(elem)
elif isinstance(elem, list):
res += get_As(elem)
return res

i also have a Tree class in my rc:
http://home.comcast.net/~faulkner612/programming/python/pythonrc.py

yomgui wrote:
 Hi,

 I have a list of data (type A)
 my list can includes element of type A or a lists,
 these list can includes element of type A or a lists, and so on ...

 is there a simple way to obtain a single list of all the elemets
 of type A ?
 
 thanks
 
 yomgui

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


Re: list of lists of lists ....

2006-07-28 Thread faulkner
doh.
ok, so, recursion is just functional programming sugar for a loop.
def get_As(L):
checking = [elem for elem in L if isinstance(elem, list)]# the
equivalent of elem in recursion
all_As = [elem for elem in L if isinstance(elem, A)]
while checking:
new_checking = []   # all lists in all lists in checking
for sub_L in checking:
for elem in sub_L:
if isinstance(elem, A):
all_As.append(elem)
elif isinstance(elem, list):
new_checking.append(elem)
checking = new_checking
return all_As


yomgui wrote:
 I forgot the most important, I am looking for a non recursive method.

 thanks

 yomgui

 yomgui wrote:
 
  Hi,
 
  I have a list of data (type A)
  my list can includes element of type A or a lists,
  these list can includes element of type A or a lists, and so on ...
 
  is there a simple way to obtain a single list of all the elemets
  of type A ?
  
  thanks
  
  yomgui

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


Re: Client/Server Question

2006-07-28 Thread faulkner
i highly doubt it.
http://www.google.com/search?domains=www.python.orgsitesearch=www.python.orgsourceid=google-searchq=os+system+deprecatesubmit=search


[EMAIL PROTECTED] wrote:
 Is os.system() going to be deprecated in future ?.I read somewhere.

 Dennis Benzinger wrote:
  [EMAIL PROTECTED] wrote:
   My server.py looks like this
  
   -CODE--
   #!/usr/bin/env python
   import socket
   import sys
   import os
  
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   host = ''
   port = 2000
  
   s.bind((host,port))
   s.listen(1)
   conn, addr = s.accept()
   print 'client is at', addr
  
   while True:
 data = conn.recv(100)
 if (data == 'MaxSim'):
 print 'MaxiSim'
 os.system('notepad')
 elif (data == 'Driving Sim'):
 print 'Driving Sim'
 os.system('explorer')
 elif (data == 'SHUTDOWN'):
 print 'Shutting down...'
 os.system('shutdown -s')
 conn.close()
 break
   ---CODE
   END-
  
   I am running this above program on a windows machine. My client is a
   Linux box. What I want to achieve is that server.py should follows
   instructions till I send a 'SHUTDOWN' command upon which it should shut
   down.
  
   When I run this program and suppose send 'MaxSim' to it, it launches
   notepad.exe fine, but then after that it doesn't accept subsequent
   command. I want is that it should accept subsequent commands like
   Driving Sim and launch windows explorer etc untill I send a 'SHUTDOWN'
   command.
  
   Any help on this, it will be greatly appreciated.
  
 
 
  os.system() blocks until the called program has finished. Use the
  subprocess module http://docs.python.org/lib/module-subprocess.html:
 
  untested_code
 
  import subprocess
 
  subprocess.Popen(notepad)
  
  /untested_code
  
  
  Dennis

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


Re: Client/Server Question

2006-07-28 Thread faulkner
you might want to look at sshd. if you're on a windows box, you may
need cygwin. if you're on linux, you either already have it, or it's in
your package manager.

[EMAIL PROTECTED] wrote:
 My server.py looks like this

 -CODE--
 #!/usr/bin/env python
 import socket
 import sys
 import os

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 host = ''
 port = 2000

 s.bind((host,port))
 s.listen(1)
 conn, addr = s.accept()
 print 'client is at', addr

 while True:
   data = conn.recv(100)
   if (data == 'MaxSim'):
   print 'MaxiSim'
   os.system('notepad')
   elif (data == 'Driving Sim'):
   print 'Driving Sim'
   os.system('explorer')
   elif (data == 'SHUTDOWN'):
   print 'Shutting down...'
   os.system('shutdown -s')
   conn.close()
   break
 ---CODE
 END-

 I am running this above program on a windows machine. My client is a
 Linux box. What I want to achieve is that server.py should follows
 instructions till I send a 'SHUTDOWN' command upon which it should shut
 down.

 When I run this program and suppose send 'MaxSim' to it, it launches
 notepad.exe fine, but then after that it doesn't accept subsequent
 command. I want is that it should accept subsequent commands like
 Driving Sim and launch windows explorer etc untill I send a 'SHUTDOWN'
 command.
 
 Any help on this, it will be greatly appreciated.

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


Re: Looking for a regular expression for this...

2006-07-28 Thread faulkner
idk, most regexes look surprisingly like undergrowth.

malahal, why don't you parse s into a dict? read each couple of lines
into a key-value pair.


John Machin wrote:
 [EMAIL PROTECTED] wrote:
  Hi,
  My string is a multi line string that contains filename
  filename\n and host host\n entries among other things.
 
  For example: s =  filename X
  host hostname1
  blah...
  host hostname2
  blah...
  filename Y
  host hostname3
  
  Given a host name, I would like to get its filename (The closest
  filename reading backwards from the host line). I could read each line
  until I hit the host name, but I am looking for an RE that will do job.

 Looking for? REs don't lurk in the undergrowth waiting to be found. You
 will need to write one (unless some misguided person spoon-feeds you).
 What have you tried so far?

  The answer should be Y for host hostname3 and X for either host
  hostname1 or hostname2.
  
  Thanks in advance.
  
  --Malahal.

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


Re: binding more than one attribute in a facntion

2006-07-26 Thread faulkner
http://cheeseshop.python.org/pypi/functional

learn lisp/scheme!
http://cs.wwc.edu/KU/PR/Scheme.html


Peter Otten wrote:
 [EMAIL PROTECTED] wrote:

  I want to have a bound method that fixes more than one parmeter of a
  funtion. LEt me post an example.
 
  def f(a, b, c):
  return a + b + c
 
  I can do:
  fplus10 = f(10)
  and then call f with 2 params and it works.
 
  But, how can I fix 2 params:
  fplus10plus20 = f(10,20)
  ignores the second param.
 
  fplus10plus20= fplus10(20)
  does not work either.
 
  Can anybody show what I'm doing wrong?

 Bound methods are limited to one implicit parameter. What you need is
 partial function application:

  def f(a, b, c):
 ... return a + b + c
 ...
  def partial(f, *args):
 ... def g(*more):
 ... return f(*args+more)
 ... return g
 ...
  partial(f, 1, 2)(3)
 6
  partial(f, 1)(2, 3)
 6
  partial(f)(1, 2, 3)
 6
 
 See http://www.python.org/dev/peps/pep-0309/ for more.
 
 Peter

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


Re: splitting words with brackets

2006-07-26 Thread faulkner
re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)

Qiangning Hong wrote:
 I've got some strings to split.  They are main words, but some words
 are inside a pair of brackets and should be considered as one unit.  I
 prefer to use re.split, but haven't written a working one after hours
 of work.

 Example:

 a (b c) d [e f g] h i
 should be splitted to
 [a, (b c), d, [e f g], h, i]

 As speed is a factor to consider, it's best if there is a single line
 regular expression can handle this.  I tried this but failed:
 re.split(r(?![\(\[].*?)\s+(?!.*?[\)\]]), s).  It work for (a b) c
 but not work a (b c) :(
 
 Any hint?

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


Re: splitting words with brackets

2006-07-26 Thread faulkner
er,
...|\[[^\]]*\]|...
^_^

faulkner wrote:
 re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)

 Qiangning Hong wrote:
  I've got some strings to split.  They are main words, but some words
  are inside a pair of brackets and should be considered as one unit.  I
  prefer to use re.split, but haven't written a working one after hours
  of work.
 
  Example:
 
  a (b c) d [e f g] h i
  should be splitted to
  [a, (b c), d, [e f g], h, i]
 
  As speed is a factor to consider, it's best if there is a single line
  regular expression can handle this.  I tried this but failed:
  re.split(r(?![\(\[].*?)\s+(?!.*?[\)\]]), s).  It work for (a b) c
  but not work a (b c) :(
  
  Any hint?

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


Re: Search within running python scripts

2006-07-24 Thread faulkner
IPC via files, sockets, and shared memory are all readily available in
python.
the simplest way is to have the script write its pid to a certain file.

pidfn = '/tmp/hellowerld_ipc_pid'
if os.path.isfile(pidfn):
f = file(pidfn)
pid = f.read()
f.close()
if pid in os.popen('ps -A -o pid').read():
print another instance of me is running!
else:
f = file(pidfn, 'w')
f.write(str(os.getpid()))
f.close()


gmax2006 wrote:
 Hi,

 Is it possible that a python script finds out whether another instance
 of it is currently running or not?
 
 Thank you,
 Max

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


Re: Note on PEP 299

2006-07-21 Thread faulkner
http://home.comcast.net/~faulkner612/programming/python/mainer.py
turns
if __name__ == '__main__': sys.exit(main(sys.argv))
into
import mainer

[EMAIL PROTECTED] wrote:
 I don't like much the syntax of:
 if __name__ == '__main__':

 Some time ago I have read this PEP:
 http://www.python.org/dev/peps/pep-0299/

 And why it was refused:
 http://mail.python.org/pipermail/python-dev/2006-March/062955.html

 I think the name of the standard main function may be just main(), so
 there isn't the problem with the import (and *maybe* the problem with
 multiple Python versions can be ignored with Python 3.0).

 If a module contains the main(), the main() is executed when the module
 is run alone. Otherwise you can import the module, with the main()
 function managed as a normal function.
 
 Bye,
 bearophile

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


Re: Python newbie needs constructive suggestions

2006-07-21 Thread faulkner
optional arguments.
map(lambda x, one=1: x + one, ...)

it is entirely possible, however, to implement let in python.
def let(**kw):
sys._getframe(2).f_locals.update(kw)

def begin(*a):
return a[-1]

map(lambda x: begin(let(one=1), x+one), range(10))

i really should warn you, though, that most pythoneers will cringe at
code like that, no matter how well they understand it. write python in
python, and you'll have more friends.


[EMAIL PROTECTED] wrote:
 What is the idiomatically appropriate Python way to pass, as a function-type 
 parameter, code that is most clearly written with a local variable?

 For example, map takes a function-type parameter:

map(lambda x: x+1, [5, 17, 49.5])

 What if, instead of just having x+1, I want an expression that is most 
 clearly coded with a variable that is needed _only_ inside the lambda, e.g. 
 if I wanted to use the name one instead of 1:

map(lambda x: (one = 1  x+one), [5, 17, 49.5])

 This sort of thing is of course straightforward in many other languages with 
 anonymous functions (Scheme, Haskell, Smalltalk, etc), and I saw in the 
 archives the discussion from 2003 about How do I get Scheme-like let 
 bindings in Python. Many of the answers seem to boil down to You should not 
 write Scheme programs in Python, you should write Python programs in Python. 
 As someone new to Python, I'd like a little more detail on this, so I'm 
 asking _what_ I should do when I want to pass, to something like map, code 
 that is most clearly expressed with a local variable?

 Do I

   a) give up on using a local variable and just substitute the value in its 
 place (going back to my original use of map),

   b) give up on using an anonymous function and create a named successor 
 function with def,

   c) give up on making one local to the lambda and create it in the scope 
 in which I'm calling map, even if I don't otherwise need it there,

   d) give up on using Python and go back to Scheme, or

   e) do something else clever and Pythonic that I don't know about yet?

 What is the idiomatically correct way to do this in Python?

 Thanks for any constructive advice you can give,
   Dave Wonnacott


 P.S., For those who want a bit more context about what I'm doing, I'll 
 provide it -- anyone else is welcome to skip the rest of this message.


 As you may guess, I am in the process of learning Python. I have some 
 experience with C/C++ and Scheme and other forms of Lisp, as well as passing 
 familiarity with a bunch of other languages.

 I teach an introductory CS course in which I cover a variety of topics that I 
 believe are central to computer science and can be expressed in any language, 
 such as algorithm design, unit and integration testing, writing code that 
 maintains an invariant property of a set of variables. However, I do not like 
 the language-free or all-pseudocode approach to teaching -- I believe all 
 examples should be shown in a real language, and that the code should be as 
 true to the customary idioms of that language as possible. This limits my 
 choice of language somewhat, since I include elements of functional 
 programming, imperative programming, and object-oriented programming -- I'm 
 not happy doing things like cramming functions into unnecessary classes in 
 Java. However, I currently believe that Python will be at least as good as 
 C++ for what I want to do, and am exploring the details of how it would work 
 out.

 One of the things I'm doing is discussing various styles of thinking about 
 the execution of an algorithm, specifically as a process of textual 
 substitution of equals for equals (as one would generally do in Haskell or 
 other functional languages, or in mathematics) or a sequence of ordered steps 
 to be followed (as one would generally do in imperative languages). Note 
 that, while Haskell programmers may say that substitution is the true way 
 that their programs are executed, and C++ programmers may say that a sequence 
 of ordered steps is what's really going on, the actual process of going 
 from your source code to the output of your program can be blending of these 
 two techniques -- for example, a C++ compiler may perform substitution where 
 it is legal to do so, producing a machine language program that is executed 
 _mostly_ in order (though a processor may commute the order of execution 
 where it is legal to do so). Anyway, in almost any language, there are _some_ 
 ways to per!
 fo!
  rm substitutions without changing the result of a piece of code (e.g. 
 substituting the value of a variable that is only assigned once, for each of 
 its uses), and some things that can be visualized in terms of execution of 
 steps even if one wishes to do so (even in a language like Haskell).

 The question of the use of variables inside a lambda is relevant to my 
 understanding of the contexts in which one can think of Python programs in 
 terms of substitution, 

Re: restricted environment

2006-07-19 Thread faulkner
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496746
When you think of modifying the interpreter, think of the compiler
module.


Gabriele *darkbard* Farina wrote:
 Hi,

 I saw the rexec module is deprecated. I need to develop a python
 application able to run custom python code based on a configuration
 file that tells the path of the script that have to be executed. Those
 scripts can be runned simultaneously trought threading module, but the
 MUST not have any way to change the base application nor the other
 scripts behaviour.

 There is a way to reach this point without using rexec? There is a way
 to start a python interpreter from python to run the scripts?

 My final goal is to develop a simple fastcgi script that, based on
 configuration files, is able to host different applications without
 need to copy the script for any application and with any risk that the
 scripts will ifluence in any way each other.
 
 Any help?
 
 Gabriele

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


Re: tkinter help

2006-07-18 Thread faulkner
add a xscrollcommand and/or yscrollcommand keyword argument to the
construction of your listbox.

def func(*a):
print i'm a callback!

L = Tkinter.Listbox(root, yscrollcommand=func)# note no parens
after func


groves wrote:
 hi eveyrbody , i have started working on python tkinter,
 While I was working on one of the tkinter classes..named listbox
 widget. I had a slight problem.

 Now let me tell you that i was able to create a simple listbox which
 had 6 options which one can select, but Now what I want is that from
 the available menu, if I select an option it should give me another
 menu associated with that option. Its like digging up that option to do
 advance search.

 Please I need help as I am making my project
 Thanks to eveyrbody who will take time to read this and solve it .

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


Re: Starting a GUI application out of an console application

2006-07-17 Thread faulkner
put your gui application in another script and start it the same way
you'd start any other application whose exit status you didn't need:
os.popen* or subprocess.Popen.
or, use the threading module to give your qt application another
thread.


Fabian Steiner wrote:
 Hello!

 I am currently working on an alternative for the gnome-volume-manager
 for multiseat systems based on HAL and DBus. Whenever the signal
 'DeviceAdded' is received I would like to start a GUI-Interface where
 the user can choose from different options. But now I am wondering how I
 should start this interface since this GUI must be started by a console
 daemon. What is the most common way to do that?

 Usually, I start a PyQt application that way:

 app = QApplication(sys.argv)
 ui = Dialog()
 app.setMainWidget(ui)
 ui.show()
 app.exec_loop()

 If I start it that way, I am not quite sure whether this will work since
 I have got two main loops then (the one of console daemon [implemented
 by using gobject.MainLoop().run()] and the Qt one). Moreover, once the
 Qt application is started, it should run independently of the console
 daemon.

 Unfortunately, I can't think of any possibility to achieve this aim. Do
 you have any suggestions?

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


Re: help!

2006-07-11 Thread faulkner
os.popen*
os.system
subprocess.Popen


Emily Ecoff wrote:
 Hi all.

 I am somewhat new to the python programming language but I'm working on
 a python script that will call several csh scripts.  What commands will
 I need to do this, if possible?
 
 -Emily

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


Re: threading troubles

2006-07-10 Thread faulkner
you don't need twisted to run processes in the background, either.
os.popen* returns a file or set of files representing std streams
immediately
subprocess.Popen is a spiffy little object new in 2.4 and available for
download for 2.3. check the module docstrings for usage tips.

you can use threads, but try doing it the python way instead of the
java way. ;-)
def func(cmd, callback):
os.system(cmd)
callback()
xc = threading.Thread(target=func, args=(cmd, callback))
xc.start()


sreekant wrote:
 Hi folks

 What am I doing wrong in the following? I just want to run fluidsynth in
 the background.
 #
 class MyThread(threading.Thread):
  def __init__(self, cmd, callback):
  self.__cmd = cmd
  self.__callback = callback
  threading.Thread.__init__(self)

  def run(self):
  os.system(self.__cmd)
  self.__callback('abcd')
  return


 cmd=midiplay+' '+fmidi
 xc=MyThread(cmd,addlog)
 xc.start()


 ##
 midiplay is 'fluidsynth -ni /home/mysndfont.sf2 mymidi.mid'
 addlog is a function which prints the log.

 If I run it only with xc.start() it does not run the program as in
 os.system. However if I  put
 xc.start()
 xc.run()

 then it starts and runs it in foreground with my pygtk ui non responsive.
 
 What am I missing!
 
 Thanks for any ideas
 sree

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


Re: WANTED: logging of all file operations on Windows

2006-07-09 Thread faulkner
you want a directory watching daemon. it isn't hard at all to build
from scratch.
first, determine which directories should be watched.
then, os.walk each directory, building a mapping from filename to mtime
[modified time; os.path.getmtime].
next is your main event loop. this while loop consists of os.walk-ing
each directory again, comparing the current mtime to the corresponding
entry in the mapping. if they differ, or if a filename isn't in the
mapping, something happened, at which point you can logick out whether
a file was moved, deleted, changed, or created.

so many folks have looked for this that i'll just write a generic one
and put it in the cheeseshop. look for dirmon in about a week.


Claudio Grondi wrote:
 I am aware, that it is maybe the wrong group to ask this question, but
 as I would like to know the history of past file operations from within
 a Python script I see a chance, that someone in this group was into it
 already and is so kind to share here his experience.

 I have put already much efforts into this subject googling around, but
 up to now in vain. Best option I encountered yet is usage of
 the Greyware 'System Change Log' service which monitors disks for
 changes (http://www.greyware.com/software/systemchangelog/index.asp),
 but in own tests it turned out, that the created log file does not cover
 all file events as e.g. it is not possible to detect when a file is
 moved to a new directory (creation of a new file is logged, but deletion
 is not, not mentioning I would expect a file 'move' event).
 The own Windows logging service rejected to start on my XP SP2 system
 for unknown to me reasons - I don't know how to get it to work (yes, I
 have used the administrator account).

 I can't believe, that using NTFS file system in Microsoft Windows 2000
 or XP it is not possible to track file events as:

 - updating/modifying of an existing file/directory
 - deleting an existing file/directory
 - creating a new file/directory
 - _moving_ an existing file/directory (should _NOT_ be covered by the
 event duo of  deleting an existing and creating a new file/directory)
 
 Any hints towards enlightenment?
 
 Claudio Grondi

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


Re: split a line, respecting double quotes

2006-07-07 Thread faulkner
import re
re.findall('\.*\|\S+', raw_input())

Jim wrote:
 Is there some easy way to split a line, keeping together double-quoted
 strings?

 I'm thinking of
   'a b c d e'  -- ['a','b','c','d e']
 .  I'd also like
   'a b c d \ e'  -- ['a','b','c','d  e']
 which omits any s.split('')-based construct that I could come up with.
 
 Thank you,
 JIm

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


Re: split a line, respecting double quotes

2006-07-07 Thread faulkner
sorry, i didn't read all your post.
def test(s):
res = ['']
in_dbl = False
escaped = False
for c in s:
if in_dbl:
if escaped:
res[-1] += c
if c != '\\':
escaped = False
else:
res[-1] += c
if c == '\\':
escaped = True
elif c == '':
res.append('')
in_dbl = False
elif c == ' ':
res.append('')
elif c == '':
res.append('')
res[-1] += c
in_dbl = True
else:
res[-1] += c
while '' in res:
res.remove('')
return res

faulkner wrote:
 import re
 re.findall('\.*\|\S+', raw_input())

 Jim wrote:
  Is there some easy way to split a line, keeping together double-quoted
  strings?
 
  I'm thinking of
'a b c d e'  -- ['a','b','c','d e']
  .  I'd also like
'a b c d \ e'  -- ['a','b','c','d  e']
  which omits any s.split('')-based construct that I could come up with.
  
  Thank you,
  JIm

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


Re: Perl Dictionary Convert

2006-07-05 Thread faulkner
data.replace('=', ':').replace(';', ',')
then eval in a namespace object whose __getitem__ method returns its
argument unchanged.


class not_str(str):# take care of that IPF.Contact
def __getattr__(self, attr):return self + '.' + attr

class not_dict(dict):
def __getitem__(self, name):return not_str(name)

eval(data.replace('=',':').replace(';', ','), not_dict())



Tom Grove wrote:
 I have a server program that I am writing an interface to and it returns
 data in a perl dictionary.  Is there a nice way to convert this to
 something useful in Python?

 Here is some sample data:

 200 data follow
 {
   Calendar =  {
 Access =  { anyone = lr;};
 Class =  IPF.Appointment;
 Messages =  0;
 Size =  0;
 UIDNext =  1;
 UIDValidity =  287898056;
 Unseen =  0;
   };
   Contacts =  {
 Class =  IPF.Contact;
 Messages =  0;
 Size =  0;
 UIDNext =  1;
 UIDValidity =  287898056;
 Unseen =  0;
   };
 }
 
 -Tom

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


Re: import

2006-07-05 Thread faulkner
that should be __init__.py [TWO underscores].
and you might want to import sys and check sys.path [the list of
directories searched by the import mechanism].


David Jackson wrote:
 Hi all,

 I'm a real beginner with python but have what I think is a simple question.
 I am writing some simple modules and would like to place them into a
 subdirectory.  But then I cannot seem to import them.  I have tried the
 following.

 I wrote a module called fibo.py with some definitions in it (one called
 fibo).  In the same directory, I wrote another file (test.py) and began with
 import fibo.  This worked fine and I was able to use the function fibo as
 fibo.fibo.  Then, I made a directory called test and placed the file fibo.py
 in this directory.  I also placed a blank file called _init_.py into this
 directory.  I went back to the original directory and tried to import
 test.fibo but this fails.  I get the following error message:

 Traceback (innermost last)
   File ...test.py, line 1, in ?
 import test.fibo
   File ...test.py, line 1, in ?
 import test.fibo
 ImportError: No module named fibo

 Any help would be greatly appreciated.  If it makes any difference, I'm
 working on a Mac, OSX 10.3.9
 
 Thanks,
 David

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


Re: cas in python

2006-07-05 Thread faulkner
import ctypes
ctypes.cdll.find('ginac')

i like designing APIs, and i'm up for learning ctypes, so i'll help
wrap ginac using ctypes.

[EMAIL PROTECTED] wrote:
 Hello,
 from time to time, people here are asking about the computer algebra
 system (cas) in python. I wonder, is there a demand for such a thing?

 I would be interested in functionality of at least ginac, but
 something, which could easily be extended. Ginac (pyginac or swiginac)
 are fine, but it seems to me to be too complex and contains a lot of
 redundant code (imho). What I need is not a speed in the first place,
 but rather rich features and simple code which I (and others) can
 extend. I would like to experiment with new features, functions, etc.,
 but using a normal language like python (or c++). Which is quite
 difficult in ginac or maple/mathematica.

 I also (like other people here) wrote a proof of concept a year ago:

 http://ondrej.certik.cz/cas.php

 and I also (like others) don't have much time to continue on it. On the
 other hand, it really does seem possible to write it in a way, which is
 very easy to understand, yet feature rich.

 So if anyone is interested in developing such a thing, please let me
 know. Or at least what you think about it - does it make sense to write
 another cas?
 
 Ondrej

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


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread faulkner
try pexpect.
http://pexpect.sourceforge.net/

valpa wrote:
 I'm a net admin for about 20 unix servers, and I need to frequently
 telnet on to them and configure them.
 It is a tiring job to open a xterm and telnet, username, password to
 each server.

 Can I  do it automatically by python? After that, there have 20 xterm
 consoles opened and telneted to their corresponding servers. Then I
 could start to type command in these xterms.
 
 Any suggestion appreciate. Much thanks.

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


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread faulkner
try pexpect.
http://pexpect.sourceforge.net/

valpa wrote:
 I'm a net admin for about 20 unix servers, and I need to frequently
 telnet on to them and configure them.
 It is a tiring job to open a xterm and telnet, username, password to
 each server.

 Can I  do it automatically by python? After that, there have 20 xterm
 consoles opened and telneted to their corresponding servers. Then I
 could start to type command in these xterms.
 
 Any suggestion appreciate. Much thanks.

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


Re: Python sub-interpreter, security

2006-06-26 Thread faulkner
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496746

[EMAIL PROTECTED] wrote:
 Hello, I am writing a pure-Python game engine that interprets the code
 of game objects within the same process with the exec statement. My
 main goal is to make as much power available as possible and exec seems
 like the best way to do that.

 This is my proof-of-concept code(only 18 lines and some whitespace,
 including the test):

 http://people.ucsc.edu/~jhofmann/programmables.py

 I showed this to the Pygame list and recieved some interest and a
 completely different, more sophisticated implementation:

 http://codereactor.net/~shang/interpret/

 As-is, both versions are wide-open security holes. I think that I can
 patch them up if I run checks on the statements and eliminate all
 language features that pose risks. Then, features that are useful but
 not needed at their full capacity can be accessed through functions
 designed to be secure. Forcing a crash is not considered an exploit for
 this purpose(since it's a game engine - if it crashes, the user can
 recover and lose no data)

 What I'd like to know is, is it possible to meet this level of
 security, and if so, which features have to be eliminated?

 The two that I'm sure should go are module imports and self-modifying
 code. But in the latter case, I don't know all the ways that might be
 done. It seems like a very complicated problem, and if I can't solve it
 I might leave the whole thing unsecured.

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


Re: Python taught in schools?

2006-06-25 Thread faulkner
Franklin W. Olin College of Engineering
I TAed a python class last semester, and am using it to build a webapp
for the Arts and Humanities dept.
http://www.olin.edu

MilkmanDan wrote:
 I'll be a college freshman this fall, attending Florida Institute of
 Tech studying electrical engineering.

 I was considering taking some classes in programming and computer
 science, and I happened to notice that everything taught is using C++.
 After further research, it seems to me that C++ seems to be the
 dominating language in universities.

 By comparison, our local community college teaches a few classes in VB,
 Java, Javascript, C++, and for some reason, PASCAL.

 I'm certianly not against any of this, but out of curiousity does
 anyone know of a school that teaches Python?

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


Re: search engine

2006-06-24 Thread faulkner
http://www.voidspace.org.uk/cgi-bin/pysearch/search.py
http://www.voidspace.org.uk/
http://www.vex.net/parnassus/
http://cheeseshop.python.org/pypi
http://aspn.activestate.com/ASPN/Cookbook/Python
http://www.google.com

vinodh kumar wrote:
 hai all,
  i am student of computer science dept. i have planned to
 design a search engine in python. i am seeking info about how to
 proceed further.
   i need to know what r the modules that can be used.
 
 
 -

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


Re: Segmentation fault only on Iinux

2006-06-20 Thread faulkner
if you don't know exactly which line of code causes the segfault, use
print statements to determine that. then try to either
redesign/refactor so that line isn't necessary, or protect its
operation somehow.
if you do know, tell us what it is and we might not need to see all
your code.

Kiran wrote:
 Hello All,
   In my program, I have a main thread which is the GUI (wxPython) and
 then a thread which goes and reads data from a socket.  The reason this
 is in a different thread is because the data might take some time to
 come back, and I want to have the GUI to be responsive during this
 wait.

  When I run my program in Linux,   a segmentation fault occurs.  When I
 run it in Windows XP, it works just fine.

 The main thing that would be of interest is as follows:
   The segmentation fault does NOT occur if I disable the threads and
 read the data all in 1 thread (the main thread [gui's]).  This leads me
 to believe it is some sort of threading problem related to linux.
 However, I personally dont think that it can be something wrong with my
 code, since my program runs perfectly fine in WindowsXP.  I am also
 carefully protecting data that my threads share with the MainGUI using
 a Queue and also a semaphore lock.

 I know this is kind of hard to answer without any code, but would
 anybody know of some kind of issue such as this where there is some
 threading problems with Linux and not Windows.  I am happy to send the
 code to anybody who wishes to see it.  I havent posted it here because
 it is kind of lengthy.

 Also, I should note that I think we are running Linux Kernel 2.4
 
 thanks a lot for your help,
 Kiran

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


Re: Problem Py2exe pygtk and Pil

2006-06-20 Thread faulkner
read the py2exe docs. py2exe should put everything a new user should
need in the dist directory. if it doesn't, copy the libraries [be they
.pyc or .pyd or .dll] that py2exe missed into dist.
i know for a fact that py2exe is intelligent with the gtk libraries, so
check if the PIL libraries are in the dist directory.

thomas carpentier wrote:
 Hello,

 I have created a program with a GUI ( glade). In this script I call the
 Python Imaging Library.

 I have developped this program onto linux, but il would like export it
 on Windows, however I have a problem with py2exe. If the new user has
 not python and library(PIL, GLADE) installed, it doesn't work. I don't
 know how integrate library into my setup.
 
 Thank you for your help.
 
 Thomas

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


Re: Getting external name of passed variable

2006-06-20 Thread faulkner
 import sys
 tellme = lambda x: [k for k, v in sys._getframe(1).f_locals.iteritems() if 
 v == x]
 a=1
 tellme(a)
['a']

Michael Spencer wrote:
 David Hirschfield wrote:
  I'm not sure this is possible, but it sure would help me if I could do it.
 
  Can a function learn the name of the variable that the caller used to
  pass it a value? For example:
 
  def test(x):
print x
 
  val = 100
  test(val)
 
  Is it possible for function test() to find out that the variable it is
  passed, x, was called val by the caller?
  Some kind of stack inspection?

 Perhaps, but don't try it ;-)
 
  Any help greatly appreciated,
  -David
 
 Can't you use keyword arguments?

   def test(**kw):
 ... print kw
 ...
   test(val=3)
 {'val': 3}
   test(val=3, otherval = 4)
 {'otherval': 4, 'val': 3}
  
 
 Michael

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


Re: Function definition

2006-06-19 Thread faulkner
no.
python is not C. python is interpreted, not compiled, so if you want a
function to exist when you call it, you need to define it before you
call it.
it isn't clunky, it's just how it's done.
if you want to define a 'main' function at the top of your
script/module, go for it. then you can use this:
if __name__ == '__main__': sys.exit(main(*sys.argv[1:]))

aarondesk wrote:
 I have a little .py file that has the format:


 def fxn(a):
 do stuff

 other stuff
 ...
 r = fxn(a)
 


 Now I've tried putting the function declaration after the call but the
 program wouldn't work. Is there anyway to put function declarations at
 the end of the program, rather than putting them at the beginning,
 which is rather clunky?
 
 Thanks.
 Aaron

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


Re: Passing data to system command

2006-06-18 Thread faulkner
import os, subprocess

xys = [[1,2],[3,4]]
msg = '\n'.join([str(x) + ',' + str(y) for x, y in xys])
os.popen('command', 'w').write(msg)
os.popen2('command')[0].write(msg)

p = subprocess.Popen('command', stdin=subprocess.PIPE)
p.stdin.write(msg)

help(subprocess)
help(os.popen)
help(os.popen3)


Chris Hieronymus wrote:
 Hi,

 I have a bunch of x-y data contained in an array.  I would like to
 plot the data using an
 external program (psxy in GMT).  The plotting program takes x-y
 couples as standard
 input.  How do I get the data into the system call?  I used to do
 things in csh and awk,
 i.e., something like

 awk '{some manipulations here; print $1, $2}' filename | psxy some
 options ! output.ps

 The reason I'm trying to use python is because the manipulations are
 getting too cumbersome
 in awk.  Now I have all the manipulations done in python, but I'm
 missing that last step.

 I've tried various things with os.system, popen, and subprocess, but
 so far without success.
 Does anyone know how to do this?

 chris


 
 ---
 Christoph
 Hieronymus
 [EMAIL PROTECTED]
 Associate
 Professor
 phone: (+46) 18-471 2383
 Uppsala
 University
fax:   (+46) 18-501   110
 Dept. of Earth Sciences (Geophysics)
 Villavägen 16
 SE-752 36 Uppsala,  Sweden

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


Re: Chess module blog

2006-06-18 Thread faulkner
make psyco entirely optional by putting it in a try/except block.
change INITIAL_BOARD to be a triple-quoted string.
you seem to mostly follow pep8, which is all most folks ask, but i
really like this style for docstrings:
def test():
''' hello,
this text and the quotes line up
very nicely
in a monospace font.
'''
return
pep8 says function names shouldn't be capitalized, and use underscores
to separate words, so they can be distinguished from classes [which are
CamelCase] quickly.

i would make a few small functions inside adjudicate for each cmd case,
then make a dict mapping 'fen' to the function fen, 'reset' to the
function reset, etc. faster and more modular.

Will McGugan wrote:
 Hi folks,

 I have just blogged about a Python chess module of mine that I wrote a
 while back. I plan on using it for a commerical project, but making the
 module open source. So I would be interested in comments / advice
 reagarding programming style and also optimization.

 http://www.willmcgugan.com/2006/06/18/chesspy/

 Regards,

 Will McGugan

 --
 work: http://www.kelpiesoft.com
 blog: http://www.willmcgugan.com

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


Re: Video capture from webcam on Mac?

2006-06-16 Thread faulkner
gstreamer has python bindings.
http://gstreamer.net/

Joseph Chase wrote:
 Is there a cross-platform solution for video capture from a webcam?

 I am aware of the Win32 videocapture library, but am unaware of how to
 accomplish the same functionality on the Mac side.
 
 Thanks in advance.

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


Re: Linux info

2006-06-13 Thread faulkner
os.path.realpath

TheSaint wrote:
 Hello there,

 I still learning, but I couldn't find anything which tells me where a
 symlink is pointing to.
 A part of os.system('ls -l ' + path) and cutting down to the need, I haven't
 got any specialized function.
 
 F

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


Re: what are you using python language for?

2006-06-06 Thread faulkner
i'm writing a text editor [yes, it has quite a few interesting unique
features].
URL:http://fauxlkner.sf.net
this summer, i hope to make it collaborative like gobby.

i also have a full-time job this summer at my college writing a small
database system to manage student records.

hacker1017 wrote:
 im just asking out of curiosity.

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


Re: ConfigParser, no attribute

2006-06-05 Thread faulkner
Settings.__init__ needs to call ConfigParser.SafeConfigParser.__init__
before it calls self.readfp.
Nexu wrote:
 Hello,

 I'm not sure exactly what i'm doing wrong here. I asked around on IRC
 and i was told the code is correct.
 The purpose of Settings() is that whenever Settings() or any of its
 methods are called. It should pick up the latest settings from file
 instead of returning what was in the buffer. This allow other scripts to
 change the value and my program and pick these changes up.
 Everything else should work exact same as ConfigParser().
 -
 class Settings(ConfigParser.SafeConfigParser):
   def __init__(self):
   self.filename = os.path.join(xchat.get_info('xchatdir'), 
 'nxscript',
 'nxscript.conf')
   try:
   config_file = file(self.filename, 'r')
   self.readfp(config_file, self.filename)
   if self.sections() == []:
   self.add_section('Global')
   if self.has_section('Global'):
   self.set('Global', 'ProtectME', 'false')
   config_file.close()
   except IOError:
   nx.sysmsg('Configuration file not found')

   def update_file(self):
   try:
   config_file = file(self.filename, 'w')
   self.write(config_file)
   except IOError:
   nx.sysmsg('Could not write to configuration file')
 -
 SAMPLE CODE (what i want to able to do):
 setting = Settings()
 if setting.get('Global', 'ProtectME'):
   print 'protection enabled'
 -
 ERRORS:
File /home/nexu/.xchat2/nxscript/nx.py, line 43, in ?
  setting = Settings()
File /home/nexu/.xchat2/nxscript/nx.py, line 24, in __init__
  self.readfp(config_file, self.filename)
File /usr/lib/python2.4/ConfigParser.py, line 286, in readfp
  self._read(fp, filename)
File /usr/lib/python2.4/ConfigParser.py, line 451, in _read
  if sectname in self._sections:
  AttributeError: Settings instance has no attribute '_sections'

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


Re: Adding attribute to objetcs

2006-06-05 Thread faulkner
when you set an attribute of an object, python secretly calls that
objects __setattr__ method.
class test:
def __setattr__(self, attr_name, attr_value):
print self, attr_name, attr_value
self.__dict__[attr_name] = attr_value# do what the original
__setattr__ method does.
test().fred = 'george'# prints test instance ... fred george


Miguel Galves wrote:
 Hello,

 I`m starting to learn python, and I hava a very good background in Java
 and C/C++ programming. I was reading Dive into python chapter about
 OO and I saw that in python we can do the following:

 class Person:
 pass

 joe = new Person()
 joe.name = Joe
 joe.age = 13

 It seems that it is possible to add attributes to any object instance
 in run time, as in Javascript. It seems to me that it can be a source
 of errors. One that come in my mind is the follwing:

 class Person:
 name = 

 joe = new Person()
 joe.nome = Joe

 The code above adds an attribute called nome,  but the programmer may think
 it's name.

 What is the real interest of this feature ? Is there a way to block this
 kind of error ?

 Thanks,

 Miguel
 --
 Miguel Galves - Engenheiro de Computação
 Já leu meus blogs hoje?
 Para geeks http://log4dev.blogspot.com
 Pra pessoas normais
 http://miguelgalves.blogspot.com
 
 Não sabendo que era impossível, ele foi lá e fez...

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


Re: re beginner

2006-06-04 Thread faulkner
you could write a function which takes a match object and modifies d,
pass the function to re.sub, and ignore what re.sub returns.

# untested code
d = {}
def record(match):
s = match.string[match.start() : match.end()]
i = s.index('\t')
print s, i# debugging
d[s[:i]] = int(s[i+1:])
return ''
re.sub('\w+\t\d+\t', record, stuff)
# end code

it may be a bit faster, but it's very roundabout and difficult to
debug.

SuperHik wrote:
 hi all,

 I'm trying to understand regex for the first time, and it would be very
 helpful to get an example. I have an old(er) script with the following
 task - takes a string I copy-pasted and wich always has the same format:

   print stuff
 Yellow hat2   Blue shirt  1
 White socks   4   Green pants 1
 Blue bag  4   Nice perfume3
 Wrist watch   7   Mobile phone4
 Wireless cord!2   Building tools  3
 One for the money 7   Two for the show4

   stuff
 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue
 bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless
 cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4'

 I want to put items from stuff into a dict like this:
   print mydict
 {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks':
 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7,
 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2,
 'Building tools': 3}

 Here's how I did it:
   def putindict(items):
 ...   items = items.replace('\n', '\t')
 ...   items = items.split('\t')
 ...   d = {}
 ...   for x in xrange( len(items) ):
 ...   if not items[x].isdigit(): d[items[x]] = int(items[x+1])
 ...   return d
  
   mydict = putindict(stuff)


 I was wondering is there a better way to do it using re module?
 perheps even avoiding this for loop?
 
 thanks!

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


do you have a local copy of Lython?

2006-06-02 Thread faulkner
# Lython = Miles Egan's Lisp-Python compiler.
The usual place
URL:http://www.caddr.com/code/lython/
throws a 404, and when I tried the email address in whois
mailto:[EMAIL PROTECTED]
the server threw an error.
I've asked around on a few forums, and somebody on irc.efnet.org/python
suggested posting here.
If you have a saved copy, please email it to me or link me to a working
download.
Thanks for your time,
faulkner

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


Re: check for dictionary keys

2006-06-02 Thread faulkner
def all(s):
for x in s:
if not x: return False
return True


bad_combos = [['-A', '-B'], ['-A', '-C'], ...]
for bad_combo in bad_combos:
assert not all([bad_elem in a for bad_elem in bad_combo])

[EMAIL PROTECTED] wrote:
 hi
 in my code, i use dict(a) to make to a into a dictionary , a comes
 from user input, so my program does not know in the first place. Then
 say , it becomes

 a = { '-A' : 'value1' , '-B' : value2 , -C : value3 , '-D' :
 'value4' }

 somewhere next in my code, i will check for these..:

 1)  -A and -B cannot exist together
 2) -A and -C cannot exist together
 3) -A and -B and -D cannot exist together
 4) and lots of other combinations to check for

 how can i efficiently check for the above? At first as i do simple
 checks , i use if and else.
 But as i began to check for more combinatoiuns, it gets messy
 
 thanks.

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


Compiling

2006-02-03 Thread Simon Faulkner
Pardon me if this has been done to death but I can't find a simple 
explanation.

I love Python for it's ease and speed of development especially for the 
Programming Challenged like me but why hasn't someone written a 
compiler for Python?

I guess it's not that simple eh?

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


Python on Windows

2006-02-03 Thread Simon Faulkner
I've just written my first (simple) WxPython program - yy!

What would folks suggest is the easiest way to package it to run on 
other windows PCs?

I would love a single .exe file that would run without ANY OTHER FILES 
even if it was 50 Mb!

TIA


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


Re: Compiling

2006-02-03 Thread Simon Faulkner
I love Python for it's ease and speed of development especially for the
Programming Challenged like me but why hasn't someone written a
compiler for Python?
 
 
 But there *is* a compiler for Python.
 http://www.python.org/doc/2.4.2/lib/module-compiler.html

ty Bruno, I must confes that I don't understand much of that chapter!

I will work harder... :-)


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


CygWin ODBC

2005-05-27 Thread Simon Faulkner
Hi All,

I am new to Cygwin and am hoping that someone here will be able to tell 
me how to get ODBC running in Python on Cygwin.

Maximum gratefullness...


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


Re: CygWin ODBC

2005-05-27 Thread Simon Faulkner
Steve Holden wrote:
 Simon Faulkner wrote:
 
 Hi All,

 I am new to Cygwin and am hoping that someone here will be able to 
 tell me how to get ODBC running in Python on Cygwin.

 Maximum gratefullness...


 Simon
 
 
 There's a trick to this which involves recompiling from source. If you 
 aren't experienced with Unix/Linux this might seem a bit intimidating.
 
 The latest version I worked on is mxODBC 2.0.7. If Egenix have released 
 something later it may incorporate these changes. Sorry they aren't 
 diff -c format.
 
 I also remember the need in the past to rename some .cpp files to 
 .c, but I believe this has now been done in the distributions.
 
 regards
  Steve

Cheers Steve, I will try that next week  Ta :-)
-- 
http://mail.python.org/mailman/listinfo/python-list