Re: interactive plots

2011-07-06 Thread Steven Howe

On 07/06/2011 09:59 AM, Ian Kelly wrote:

On Wed, Jul 6, 2011 at 9:04 AM, Mihai Badoiu  wrote:

How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
and I want in the plot to be able to click on f and make it disappear.  Any
python library that does this?

Matplotlib can be integrated with either wxPython or PyQt to create
GUI applications with interactive plots.

PyGTK interface too.

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


Re: Checking against NULL will be eliminated?

2011-03-02 Thread Steven Howe
Back at NCR, they stressed the axiom '90% of the time is spent fixing 
10% of the code'.


How true that axiom is. Never more so then when faced with a programming 
language fix like PEP 4000. Fortunately for me, I never trusted python's 
complex, or should I say 'overloaded' Boolean usage.


If I want to know if a string or list dictionary is empty: if ( len(x) 
== 0 ).


If an item is None: if ( type(x) == types.NoneType ):

if truly Boolean and want to 'do' something on False, then I use 'not'.

I really like 'types'. Helps error checking, helps making logic flows 
cleaner and less error prone. And since 'pydev/Eclipse' is so good at 
finding my from/imports and inserting them for me, I use types liberally.


I guess being an old C programmer makes one a bit more cautious; nothing 
worse then compiler errors, accept runtime errors. And over course, I 
still use lots of parentheses to group my logic. Hell, I still do a lot 
of that when using bash.


So PEP 4000, go ahead, break some over indulgent code and coders; I'm 
not bothered.


Steven


On 03/02/2011 07:15 AM, Tom Zych wrote:

On Wed, 02 Mar 2011 06:37 -0800, "Carl Banks"
wrote:

The larger reason is that boolean evaluation in Python tries to be too
many things: for some types is means "not zero", for some types it
means "empty", and for some types it means "this is a value of this
type as opposed to None".  That causes conflicts when more than one of
those tests makes sense for a given type, as it does with Elements.

You're right.

PEP 4000:
Proposing a new, backwards-incompatible version of Python in which
boolean evaluation
is not so overloaded.

Hmm, no, I don't think that will fly. We're stuck with it :(

Fortunately there are work-arounds for the cases that matter, as we've
seen.
Yay Python :)



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


Re: Playing WAV file with Python

2011-03-03 Thread Steven Howe

On 03/03/2011 01:32 AM, VGNU Linux wrote:



On Thu, Mar 3, 2011 at 1:54 PM, Chris Rebert <mailto:[email protected]>> wrote:


On Thu, Mar 3, 2011 at 12:17 AM, VGNU Linux mailto:[email protected]>> wrote:
> On Thu, Mar 3, 2011 at 1:26 PM, Chris Rebert mailto:[email protected]>> wrote:
>> On Tue, Mar 1, 2011 at 11:47 PM, VGNU Linux
mailto:[email protected]>> wrote:
>> > How can I play WAV file in python without OS(like
Linux/Windows/MAC) on
>> > a
>> > device ?
>> > On Google I found lot of different solution but related to
OS's like
>> > winsound, ossaudiodev etc which are not useful.
>>
>> Do you mean you want your code to be cross-platform, or what?
>> "Without OS" is rather vague. What are you trying to accomplish?
>
> I will be using WAVE on embedded devices, and the device will
not have any
> OS's. So I am looking for modules which can play WAVE sound without
> underlying OS.

What implementation of Python are you going to use? I don't personally
know of any that can run on the "bare metal" without an OS.


I am planning to use python-on-a-chip(PyMite) which can be run without 
an OS therefore I am looking for a module/library which can play sound 
files.



Cheers,
Chris


As you wont be calling the OS via subprocess, which is about the only 
way to fire up some connect to the sound system, you probably should be 
talking about the pymite issues on the pymite group over at google about 
drivers (i.e. sound drivers), what data types (wav, mp3, ogg) they will 
take and how to pass data to a driver. The


nbed.AnalogOut looks intriguing. Perhaps you can spool a wav file to a port, 
attach the
analog out to an external amplifier.

http://groups.google.com/group/python-on-a-chip?pli=1

Also, perhaps you should be looking atArduino and audio projects.

http://www.ladyada.net/make/waveshield/




Good luck,

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


Re: checking if a list is empty

2011-05-11 Thread Steven Howe

On 05/11/2011 02:47 PM, Steven D'Aprano wrote:

On Wed, 11 May 2011 20:13:35 +0100, Hans Georg Schaathun wrote:


One principle of object oriented programming is to bestow the objects
with properties reflecting known properties from the domain being
modelled.  Lists do not have truth values in the application domain

Yes they do. Empty lists are nothing, ergo false, and non-empty lists are
something, ergo true.


>>>  a=[]
>>>  if a:
... print 'Yes'
...
>>>  a=[1]
>>>  if a:
... print 'Yes'
...
Yes


Cool; I'd never of thought to try that method to determine if a list was 
empty. I usually test it's length.

This looks faster.


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


Re: comparison with None

2007-04-18 Thread Steven Howe
Alan G Isaac wrote:
>  >>> None >= 0
> False
>  >>> None <= 0
> True
>
> Explanation appreciated.
>
> Thanks,
> Alan Isaac
>   
I've read and found that 'None' comparisons is not always a good idea.
Better to:
from types import NoneType

x = None
if type( x ) == NoneType:
# true
    < code >
else:
# false; do something else.
< more code >

Steven Howe

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


Re: comparison with None

2007-04-18 Thread Steven Howe

Alan Isaac wrote:

"Terry Reedy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
  

Should be in the reference manual section on comparisons.



Only to this extent:
http://www.python.org/doc/2.4/ref/comparisons.html

objects of different types always compare unequal, and are ordered
consistently but arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in
operators.
In the future, the comparison rules for objects of different types
are
likely to change.)

...  Most other types compare unequal unless they are the same
object;
the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one
execution
of a program.

This does not provide a direct answer to "why" None comparisons.
(As far as I can tell, None is less than any object.)

However, Gary Herron's explanation makes sense: this provides a stable
sort when None is involved, and meets the criterion that objects of
different types must always compare unequal.  However this would also
be true if None always compared greater than any object, and the current
behavior does not seem to be guaranteed.

Is that about right?

Cheers,
Alan Isaac


  
I love scripting languages ... but sometimes an explicit evaluation that 
one would find in

a compiled language is better.
Which is why I suggested using the explicit type(x) == types.NoneType as 
opposed to

x is None


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

Re: Byte-Array to String

2007-04-19 Thread Steven Howe

Robert Rawlins - Think Blue wrote:

Hello Guys,

 


I have a byte array passed to me by dbus and I'm looking to convert it into
a string? Is that possible? Sorry for seeming like a putts with these
questions, I'm not used to all these complex data types :-D

 


The byte array looks something like this when printed to screen.

 


dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9),
dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu
s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0),
dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus.
Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0),
dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By
te(1)], signature=dbus.Signature('y'))

 


Thanks again,

 


Rob
*
*
When reading about array, I wondered what the hell it was good for. Now 
I see. It's a tool to build objects
to pass to the Operating System or other applications. Something like 
ctypes. The OS might store data from left to right, or right to left, or 
not use IEEE standards (which VMS certainly doesn't). So the data you 
give/get from the system call must be massaged by the application before 
it's usable.


python/lib/module-array.html (5.14 array -- Efficient arrays of numeric 
values)

*array.tostring*( )
/Convert the array to an array of machine values and return the string 
representation (the same sequence of bytes that would be written to a 
file by the tofile() method.)/


I wonder if this is the method you are looking for.
So you have an object dbus.Array, which, obviously is from a call to the 
dbus (another application's data) that contains 28 byte arrays. I would 
assume you know which you want, say the first one.


   myDbusString01 = dbus.Array[0].tostring()

or to get the lot:

   myDbusStrings = []  #create a new empty list
   for array in dbus.Array:
   myDbusStrings.append( array.tostring() )

At this point you should have the array converted. But you will still 
need a reference as to what you have. The call to the dbus should have 
some documentation abut what it's returning.
Also I'd expect the second example to be very bad programming, as some 
of the array elements are probably not going to be characters. They 
could be integers, floats or booleans. So creating a dictionary to 
handle specific array element handling is probably a better, less error 
prone, method of attack.


Not have the contents and defination of your dbus.array handy, I can't 
test this, but the approach seems reasonable.


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

Re: comparison with None

2007-04-19 Thread Steven Howe

Steven D'Aprano wrote:

On Thu, 19 Apr 2007 08:18:30 -0400, Steve Holden wrote:

  
Which is why I suggested using the explicit type(x) == types.NoneType as 
opposed to

x is None


  
This seems to go entirely against the spirit of the language. It's about 
as sensible as writing


   (3 > 4) == True




Please! For extra certainty, you should write that as:

((int(3) > int(4)) == True) == True

Explicit is better than sensible, yes?

*wink*



  
Your example, even with the *wink*, is stupid. The language requires 3 
to be an integer, 4 to be an integer.



The point I was show is with respect to a returned variable (like from a 
function or method? *wink* *wink*).
For example, if you expect an open file handle, but get a NoneType 
because you didn't really open a file (having given a bad name or maybe 
didn't have permission to open a file), then it would be best to test 
the type of return object before using it. Then you program could handle 
the error gracefully (*wink* *wink* *wink*).


As much as I love Python, it's ability to morph an object type can be a 
pain. Testing before using can prevent a program from Error-ing out.


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

Re: If Dict Contains a particular key

2007-04-24 Thread Steven Howe
Carsten Haese wrote:
> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote:
>   
>> Hello Guys,
>>
>>  
>>
>> I’m Looking to build a quick if/else statement that checks a
>> dictionary for a key like follows.
>>
>>  
>>
>> If myDict contains ThisKey:
>>
>> Do this...
>>
>> Else
>>
>> Do that...
>> 
>
> I'm pretty sure you'll find the answer to this question somewhere in
> http://docs.python.org/tut/tut.html
>
> -Carsten
>
>
>   
or try:
thedict = { 'a': 1, 'b':2, 'c':3 }
if 'a' in thedict.keys():
print thedict['a']

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

Re: Catching a specific IO error

2007-04-24 Thread Steven Howe
Steve Holden wrote:
> Thomas Krüger wrote:
>   
>> Tina I schrieb:
>> 
>>> Now, this works but of course it catches every IOError, and I can not
>>> figure out how to restrict it to only catch the "[Errno 2]"?
>>>   
>> There's an example that uses the error number:
>> http://docs.python.org/tut/node10.html#SECTION001030
>>
>> 
> So what you'll need to do is catch all IOError exceptions, then test to 
> see if you've got (one of) the particular one(s) you are interested in. 
> If not then you can re-raise the same error with a bare "raise" 
> statement, and any containing exception handlers will be triggered. If 
> there are none then you will see the familiar traceback termination message.
>
> regards
>   Steve
>   
you could also use some pre-testing of the filename  os.path.isfile, 
os.path.isdir, os.path.split are good
functions to test file/directory existence. Also to verify that you have 
permission to manipulate a file, os.access is a good function.
sph


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


Re: RPM error

2007-04-24 Thread Steven Howe
CSUIDL PROGRAMMEr wrote:
> Hi folks
> I am new to python
> I am trying to write a program that will install rpm
> using rpm -ivh xxx.rpm
>
> I want to know if python has in-built exceptions  to catch no-
> dependencies error.
>
> If not how can i build them
>
> thanks
>
>   
not really sure where your going with this... but
you could use popen3 to redirect the StdError and StdOut of rpm to 
files. Then read those
files (in particular StdError) for dependency output

*popen3*(   cmd[, mode[, bufsize]])

Executes cmd as a sub-process. Returns the file objects
|(child_stdin, child_stdout, child_stderr)|. Availability:
Macintosh, Unix, Windows. New in version 2.0. 
if your app doesn't wnat to wait, you can use os.spawn functions

*P_NOWAIT*

*P_NOWAITO*
Possible values for the mode parameter to the spawn*() family of
functions. If either of these values is given, the spawn*()
functions will return as soon as the new process has been created,
with the process ID as the return value. Availability: Macintosh,
Unix, Windows. New in version 1.6. 

*P_WAIT*
Possible value for the mode parameter to the spawn*() family of
functions. If this is given as mode, the spawn*() functions will not
return until the new process has run to completion and will return
the exit code of the process the run is successful, or |-signal| if
a signal kills the process. Availability: Macintosh, Unix, Windows.
New in version 1.6. 

sph


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


Re: popen2 results

2007-04-25 Thread Steven Howe

Robert Rawlins - Think Blue wrote:

Hello guys,

 


I've recently ported my application from bash to python, however there are
still a few bash line utilities I -have- to use in the application as there
isn't any alternative available to me. In the old days of bash I would have
grep'd the output from these commands to determine the outcome.

 


I'm now using popen2 to run the command which works a charm, but I'm
struggling to parse the results of the function, has anyone had any
experience with this? I've found a few suggested solutions dotted around,
such as this one.

 


 import os

 


 def filtered(command, source):

 dest, result = os.popen2(command)

 dest.write(source)

 dest.close()

 try:

  return result.read()

 finally:

  result.close()

 


But to be honest I'm struggling to get it to do anything as it doesn't
states what the 'source' object is or should be.

 


Thanks for any help guys, I'm just looking to capture the output from the
command and then I can go about a little REGEX on it.

 


Thanks,

 


Rob


  
check out os.popen3 as well. An Example? Let's assume you were doing 'ls 
-1', which at the
console would give you a one column list of files (and yes, I know I can 
use glob.glob for this;

this is an example).

   from os import popen3
   ( sin, sout, serr ) = popen3( 'ls -1 /tmp' )
   fList = sout.readlines()
   for f in fList:
   print f
   errors = serr.readlines()
   for line in errors:
   print line


Now you have 3 file handles.
sin: input (which I've never used, as I give popen3 a complete command)
sout: the standard output stream
serr: the standard error output
You can read sout and serr and take action on them.
Oh and each line has a '\n' linefeed (probably '\r\n' on Windows). 
Depending on what your doing
with the output, you might want to use string.strip to eliminate the 
linefeeds.


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

Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Steven Howe
Grant Edwards wrote:
> On 2007-04-25, Chris Mellon <[EMAIL PROTECTED]> wrote:
>
>   
>> "Returning memory to the OS" doesn't affect exhaustion of your virtual
>> address space. More likely, your nested loops are just creating more
>> objects than is possible to hold within a single process.
>> 
>
> I'm a bit fuzzy on this, but I don't think there _is_ a
> practical way to "return memory to the OS" in many OSes.  For
> example in Unix the C library uses the sbrk() call to increase
> the size of the data segment when additional memory is needed
> to handle soemthing like malloc() calls.  
>
> In theory, one can use brk() to reduce the size of the data
> segment, but I think making the segment smaller will produce
> undefined behavior if any of the standard C library's dynamic
> memory routines (e.g. malloc/free) have ever been used by the
> program prior to the call to brk().
>
>   
Interesting questions. What happens when an object is 'cleaned' up by
using the 'del' command. Does the memory space stay in the python
process, get handed back to the OS, or some combination of both?
I remember 'C' on VMS at least, could be coerced into return memory on
block boundaries. 'C++' was suppose to have garbage collect, but I was
always doubtful it worked well.

sph

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


Re: My python annoyances so far

2007-04-26 Thread Steven Howe
[EMAIL PROTECTED] wrote:
>> Well, why do some things in the library have to be functions, and
>> other things have to be class methods?
>> 
Perhaps because some things are more naturally function like? For 
'instance' (pardon the pun), functions shouldn't retain data. They 
perform an operation, return data and quit. While retaining data is a 
feature of an class/instance.

If I'm looking up the time of day in L.A., why do I need the whole clock 
database of times including New York and London?

Another example are with respect to  'int' and 'float' operations. Why 
should int(x) be a class? Did you want to save and operate on the value 
of x again? No, you want the integer portion of x. Ditto float(x); 
somebody input '5' but you want it clear it 5.0. You typecast it your 
way. But the float operation doesn't need to retain the last input, nor 
even exist after it's last use. So, without have any current values 
referenced inside 'float', garbage collection can recover the memory 
space of 'float'.

And before someone get's all technical, I know everything in Python is 
an 'object' even None, which implies class, or is it the other way around?

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


Re: getting rid of EOL character ?

2007-04-27 Thread Steven Howe

stef wrote:

hello,

In the previous language I used,
when reading a line by readline, the EOL character was removed.

Now I'm reading a text-file with CR+LF at the end of each line,
Datafile = open(filename,'r') 
line = Datafile.readline()


now this gives an extra empty line
print line

and what I expect that should be correct, remove CR+LF,
gives me one character too much removed
print line[,-2]

while this gives what I need ???
print line[,-1]

Is it correct that the 2 characters CR+LF are converted to 1 character ?
Is there a more automatic way to remove the EOL from the string ?

thanks,
Stef Mientki
  

>>> abcd = 'abcdedff . \n'
>>> abcd
'abcdedff . \n'
>>> print abcd
abcdedff .

>>>* from string import strip*
>>> print abcd.strip()
abcdedff .
>>> a = abcd.strip()
>>> a
'abcdedff .'
>>>

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

Re: How can I save command prompt screen

2007-04-27 Thread Steven Howe

ozan SARI wrote:

Hi ,
 
I  run  a  python  acript   with os.system('script.py')
 
I  want   save command prompt screen  in  a  text file (everything )   
how  can  I  do  this?
 
Thanks   for your  help
 
 
Ozan 
check out using the subprocess module 
http://docs.python.org/lib/node529.html  It seems 
to be the new
replacement for os.system spawn, popen  It has specific stdout, 
stderr and stdin handling.


sph

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

Re: How to replace the last (and only last) character in a string?

2007-05-03 Thread Steven Howe

Dave Borne wrote:

Let's suppose
s='12345 4343 454'
How can I replace the last '4' character?



If the last '4' will not always be the last character in the string,
you could do:
'X'.join(s.rsplit('4',1))
  


   from string import rfind
   def replaceLast_X_with_Y( s, x, y ):
   lastX = s.rfind(x)
   return s[:lastX]+ y + s[lastX+1:]

   s = '12345 4343 454'
   replaceLast_X_with_Y( s, '4', '9' )
   '12345 4343 459'


sph

--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: Microsoft's Dynamic Languages Runtime (DLR)

2007-05-04 Thread Steven Howe
Fuzzyman wrote:
> On May 4, 5:27 pm, Kaz Kylheku <[EMAIL PROTECTED]> wrote:
>   
>> On May 2, 5:19 pm, sturlamolden <[EMAIL PROTECTED]> wrote:
>>
>> 
>>> On May 3, 2:15 am, Kaz Kylheku <[EMAIL PROTECTED]> wrote:
>>>   
 Kindly refrain from creating any more off-topic, cross-posted threads.
 Thanks.
 
>>> The only off-topic posting in this thread is your own (and now this
>>> one).
>>>   
>> You are making a very clumsy entrance into these newsgroups. So far
>> you have started two cross-posted threads. The first is only topical
>> in comp.lang.python (how to emulate macros in Python). This one is
>> topical in neither one, since it is about Microsoft DLR.
>>
>> It's quite possible that some Lisp and Python programmers have a
>> strong interest in Microsoft DLR. Those people who have such an
>> interest (regardless of whether they are Lisp and Python user also)
>> and who like to read Usenet will almost certainly find a Microsoft DLR
>> newsgroup for reading about and discussing Microsoft DLR. Do you not
>> agree?
>>
>> 
>
> Given that the DLR is a dynamic language framework, abstracted out of
> the IronPython 1.0 release, and that it also runs on top of the core
> CLR shipped with SilverLight meaning that for the first time sandboxed
> Python scripts can run in the browser...
>
> It would seem entirely on topic for a Python newsgroup very on-
> topic...
>
> Fuzzyman
> http://www.voidspace.org.uk/ironpython/index.shtml
>
>
>   
>> Also note that there is very rarely, if ever, any good reason for
>> starting a thread which is crossposted among comp.lang.* newsgroups,
>> even if the subject contains elements that are topical in all of them
>> (yours does not).
>>
>> 
>>> Begone.
>>>   
>> You are childishly beckoning Usenet etiquette to be gone so that you
>> may do whatever you wish. But I trust that you will not, out of spite
>> for being rebuked, turn a few small mistakes into a persistent style.
>> 
>
>
>   
Thank goodness! I was getting ready to filter the DLR crap out. If it's 
from microsoft,
it got to be crap.
sph


-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: File names and file objects [was Re: My Python annoyances]

2007-05-05 Thread Steven Howe




Steven D'Aprano wrote:

  On Fri, 04 May 2007 07:55:25 -0700, Alex Martelli wrote:

  
  

  What about the case where I have an array of objects that represent some
particular binary file format.  If the object is a file, then I want to
copy its contents.  If the object is a string, then I want to write the
string.  And so forth.
  

"Type-switching" in this way is a rather dubious practice in any
language (it can't respect the "open-closed" principle).

  
  
What do people think about functions that accept either a file name or a
file object?


def handle_file(obj):
if type(obj) == str:
need_to_close = True
obj = file(obj, 'r')
else: 
need_to_close = False
do_something_with(obj.read())
if need_to_close:
data.close()


Good idea? Bad idea? Just a matter of personal preference?



  

The first question to ask is why are you using an array to hold
multiple 
unidentified objects? Why not use a dictionary instead. You could add
items using the object as key and type as data element.
import types
dictOfObjects = {}
aString = 'abcde'
fobj = open('filename', 'w')
fout = open('anotherFilename','r')
dictOfObject[aString] = [types.StringType]
dictOfObjects [fobj] = [types.FileType, 'w']
dictOfOjbect[fout] = [types.FileType,'r']

Then you can iterate over the dictionary; selection/action by type.

The question seems kind of bogus anyway. The only language
feature that stores different elements in a single body are similar to
 'C/C++' structures. At which point one has to ask... why not use the 
struct module? Ah ... perhaps the questioner didn't know about them?

Well I'd suggest, before more 'annoyances' postings to review the
top level of the module
index @ http://docs.python.org/modindex.html.
I find it a great place to start looking for python language features
that
my programs need, but I don't know, yet.

sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0



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

Re: SEO - Search Engine Optimization - Seo Consulting

2007-05-08 Thread Steven Howe

Steve Holden wrote:

Steven D'Aprano wrote:
  

On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote:


[a request for peace, love and understanding, concluding with]
  

We all should be a little more considerate of each other.
  

And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed
to hunt them down like rabid dogs and stick their heads up on pikes as a
warning to others.

Hey, a man can dream can't he??? *wink*




Yeah, just ONE day a year when we could roast them on spits over open
fires ... just to discourage the survivors, you understand.

regards
  Steve
  

Man Steven,
you really need someone to give you a huge and possibly some sex. You're 
way too
mean and aggressive for a site where people are looking for help. Yes, 
some messages

are out of place, but 'burning the witch' talk is just way, way out there.

I suggest you join the Republican party and lose some more brain cell 
(i.e. program in

Visual Basic) or better yet, learn to filter your e-mail.

That's a thought; I think I'll filter you. :)

sph


--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: Using "subprocess" without lists. . .?

2007-05-13 Thread Steven Howe

Michael Williams wrote:

Hi All,

I've recently seen the "subprocess" module and am rather confused by  
it's requirements.  Is it not possible to execute an entire string  
without having to break them up into a list of arguments?  For  
instance, I'd much rather do the following:



subprocess.call("ls -al | grep -i test")


. . .than to have to:


list = ["ls", "-a", "-l" ]  . . . . . . and so on and so forth.
subprocess.call(list. . .)


What is the best way to go about executing a massively complex single  
line command?



Thanks,
Michael
  

How about a hybrid solution?:

   from subprocess import Popen, PIPE
   from string import strip
   (stdout, stderr) = Popen(['ls','-al'], stdout=PIPE,
   stderr=PIPE).communicate()
   /# process spins off. Ideally, you should wait for it to complete,
   or assign the resulting object of Popen
   # to a variable and inquire if it's completed via the 'poll()'
   operator or wait on it via the 'wait()'
   # operator.
   # then query the stderr via communicate()[1]; if good, i.e.
   len(stderr) == 0, inspect the resulting
   # stdout string (via communicate()[0]) for your 'test' result. But
   I'm being lazy. I assume the call to
   # ls -al will be faster then my next statement./
   res = []
   for line in stdout.strip():
   if 'test' in line:
  res.append( line )


Do the work you need done at the shell prompt, do the rest in Python. 
Also I wonder if, you were looking for the word 'test' in the filename,  
glob.glob wouldn't have been a bit more efficient? But if you were 
looking for a 'test' owner or group then using:


   glob.glob(): get the _list_ of  files, with directory. Example: 
   *glob.glob('/bin/*') *

   os.stat(): get an _object_ of stats on a file. Example:*
   os.stat('/bin/ls')*
   stat.ST_UID: get just the group id, as an _integer_ from the object
   returned by os.stat. Example: *os.stat('/bin/ls')[stat.ST_UID]
   *pwd.getpwgid(): get the _string_ translation of a UID. Example:
   *pwd.getpwgid( os.stat('/bin/ls')[stat.ST_UID] )*
   stat.ST_GID: get the group id, as an _integer_ from the object
   returned os.stat. Example:
   *os.stat('/bin/ls')[stat.ST_GID]*
   grp.getgrgid(): get the _string_ translation of a UID. Example:
   *grp.getgrgid( os.stat('/bin/ls')[stat.ST_UID] )*

Now I have a list, which I iterate over, getting the UID and GID, as 
strings, that I can compare to. I never had to use a subprocess and 
having to build up a 'wait on done loop'.  Note, grp and pwd, I think, 
are Python/Unix functions. What one does on Windows I don't know, but 
I'll bet there are similar functions under Python/Windows. Don't get me 
wrong, Subprocess is a fast and damn useful tool. I often use it to 
verify a program is in my path, before creating a subprocess to run some 
task python isn't built for (like mencoder functionality).


You see, the issue is: _shell,_ _python & shell_ or _python alone_. When 
transitioning from one language to another, say C/C++/Java to Python, it 
is often easier to use your knowledge of the shell command (bash/Bourne 
for example) to get things done. But it's only a transitional issue. The 
need to use the shell is a good demonstrator that either the Interpretor 
is weak, or that you haven't fully explored it's abilities. With the 
Python Interpretor at v2.4 going onto v2.5, it's very likely that the 
desired feature exists; you have but to do some clever research to find 
it. As to clever research ... I find Google a good place to start.


I had some familiarity with os.stat and glob. But the grp and pwd 
functions were things I discovered from 
http://docs.python.org/modindex.html and about two minutes of searching 
for 'python uid to name' @ Google.


Also, os.listdir and os.path.join would have worked just as well as 
glob.glob('dirname/*'). But glob.glob was faster to write. Even a better 
choice would have been to use the 'os.walk' to iterate over the 
directory tree.


sph.

--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: os.listdir() doesn't work ??

2007-05-14 Thread Steven Howe

Stef Mientki wrote:

hello,

I want to find all files with the extension "*.txt".
 From the examples in "Learning Python, Lutz and Asher" and
from the website I see examples where you also may specify a wildcard filegroup.

But when I try this
   files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt')

I get an error message

   WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect: 
   'D:\\akto_yk\\yk_controle\\*.txt/*.*'	


What am I doing wrong ?

thanks,
Stef Mientki
  

Hi Stef,
Like that name; from a passing thought, I think the os.listdir command 
will resolve the slash/backslash. You might try using the unix method 
which I think would be 'd:/akto_yk/yk_controls/*.txt'. I'm sorry, but I 
can't test this knowledge, as I don't have access to Windows.


Alternatively you could use glob.glob, after changing directory ( via 
os.chdir) to get a listing.


   from os import chdir, getcwd
   from glob import glob

   CWD = getcwd()
   chdir( 'd:/akto_yk/yk_controls')
   filelist = glob.glob('*.txt')
   chdir( CWD )


Steven Howe

--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: removing spaces between 2 names

2007-05-14 Thread Steven Howe
[EMAIL PROTECTED] wrote:
> Hi,
>  Suppose i have a string stored in variable,how do i remove the
> space between them,like if i have the name:
> "USDT request" in a variable.i need "USDTrequest",without any space .
> Thanks
>
>   
from string import replace
st = 'abcd acdfgxtit'
st.replace(' ','')
'abcdacdfgxtit'

sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: Trying to choose between python and java

2007-05-15 Thread Steven Howe
Anthony Irwin wrote:
> Hi All,
>
> I am currently trying to decide between using python or java and have 
> a few quick questions about python that you may be able to help with.
>
> #1 Does python have something like javas .jar packages. A jar file 
> contains all the program files and you can execute the program with 
> java -jar program.jar
>
> I am sort of hoping python has something like this because I feel it 
> makes it easier to distribute between platforms e.g. linux, mac 
> windows etc.
>
> #2 What database do people recommend for using with python that is 
> easy to distribute across linux, mac, windows.
>
> #3 Is there any equivalent to jfreechart and jfreereport 
> (http://www.jfree.org for details) in python.
>
> #4 If I write a program a test it with python-wxgtk2.6 under linux are 
> the program windows likely to look right under windows and mac?
>
> #5 someone said that they used to use python but stopped because the 
> language changed or made stuff depreciated (I can fully remember 
> which) and old code stopped working. Is code written today likely to 
> still work in 5+ years or do they depreciate stuff and you have to update?
>
> Anyway hopefully someone can help me out with these last few questions 
> I have.
>
> Also does anyone else have any useful comments about python vs java 
> without starting a flame war.
>
>
>   
Flame war? Here amongst all the reasonable adults programmers? It never 
happens.

1) I always thought jar files were weird. Change the run mode on you 
python script and just run it, over and over.
chmod u+x program.py
./program.py
No doubt you are (shudder) a Windows user (and beat yourself in the 
closet at night as well). No doubt Windows has a feature to set the 
privilege on a file to make it executable. With any luck, I'll never know.

2) Python interfaces with with damn near every database I've ever seen, 
regardless if the database is on the same system or remote. At worst 
case, it seems to have ODBC connection (yes I know, C and connect are 
the same thing, like an American saying Mount Fujiyama, which is of 
course, Mount Fuji Mount) feature. Not as precise as a targeted 
connector, but it works. There are even multiple ways to 'see' the 
database. As strings, lists, objects, rows, tables and dictionaries. 
It's all quite a powerful tool. Image, getting to choose how you 'see' 
the database. Who'd have thunk!

3) No idea about jfree. Perhaps a few keyword searchs on Google or 
Sourceforge would give you an answer.

6) Never programmed wx. But it seems to be very stable on the programs 
I've downloaded. Anyway mapping one GUI to another is always an 
imprecise effort (especially when you have 235 patents on the product 
that you dare not tell anyone about). No two mindset ever really meet, 
especially when money is involved.

5) All languages grow. Get over it. But, if you keep the older 
interpreter around, you can still run your old scripts. At NCR I had to 
support 6 different version of Perl because the programmers wouldn't 
fix/update their code. Seem they had better things to do and you can 
always expect the Sysadmin to save your bacon. 
But if you haven't got to that point (six version to support) yet, 
during pre-upgrade tests, you might run the program and note the 
features that are going to be decrepit. Generally you have a few minor 
version releases (year or more) before the decrepit feature is dropped. 
Then you can decide if upgrading/fix or running multiple version of 
python is the right path for you. Using the PYTHONPATH environment 
variable is a good way to redirect your older scripts to use decrepit 
feature via an older interpreter.

The (6) you didn't ask. As a Sysadmin, I hate Java. It's a resource hog. 
Little tasks take hundreds of megabytes of RAM. What can one expect. 
It's a virtual machine inside your computer. Hog it must be! Python is a 
bit slimmer on the memory footprint and I think a hell of a lot easier 
to debug. Even strace can be used on python programs. Never got strace 
to work on Java scripts.

The (7) you didn't ask. Last month there was a full flame war about 
java/python on the python-list. It petered out after about 15 days. You 
might review the archives to get a sense for yourself (so we don't have 
repeat the war, just for you).
 
sph


-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: Python Newbie Suggestions

2007-05-15 Thread Steven Howe
[EMAIL PROTECTED] wrote:
> I'm a mechanical engineer with little experience programming. I've
> used C++ and machine language for getting micro-controllers to work
> and thats about it. I work allot with software developers at my job
> and can read C++ code pretty good (ie. I understand whats going on).
> Does anyone have any good tips or resources for someone interested in
> learning PYTHON.  This is purely for hobby purposes and I'd like to
> expose my kids to a programing language too. If any one has any
> helpful books, tips or suggestions please let me know.  I have
> Windows, MAC and Linux box's at my house but I'm a primarily a MAC
> user.
>
>   
I found "Learning Python" O'Reilly pretty good. It's pretty dogeared 
now. It's
ISBN number is:1-56592-464-9. That's edition 1from the last century.

sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: How do I count the number of spaces at the left end of a string?

2007-05-16 Thread Steven Howe
walterbyrd wrote:
> I don't know exactly what the first non-space character is. I know the
> first non-space character will be  * or an alphanumeric character.
>
>   
using builtin function rindex
 st = 'asblde  '
 >>> st.rindex(' ')

sph


-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: how do I count spaces at the beginning of a string?

2007-05-17 Thread Steven Howe

Paul McGuire wrote:

On May 16, 9:02 pm, walterbyrd <[EMAIL PROTECTED]> wrote:


The strings start with whitespace, and have a '*' or an alphanumeric
character. I need to know how many whitespace characters exist at the
beginning of the string.
  



using buitlin function len() and lstrip()

   ax = 'asdfjlwese   asdfasl '
   len( ax ) - len( ax.lstrip() )

sph
--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: remove all elements in a list with a particular value

2007-05-17 Thread Steven Howe

MRAB wrote:

On May 16, 4:21 pm, Lisa <[EMAIL PROTECTED]> wrote:
  
I am reading in data from a text file.  I want to enter each value on

the line into a list and retain the order of the elements.  The number
of elements and spacing between them varies, but a typical line looks
like:

'   SRCPARAM   1 6.35e-07 15.00  340.00   1.10  3.0   '
  

Using builtin functions:

   ax = '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10  3.0   '
>>> ax.replace('  ','')  # replace all double spaces with nothing
   ' SRCPARAM 1 6.35e-07 15.00340.00 1.103.0 '
>>> ax.replace('  ','').strip() # strip leading/trailing white spaces
   'SRCPARAM 1 6.35e-07 15.00340.00 1.103.0'
>>> ax.replace('  ','').strip().split(' ') # split string into a
   list, using remaining white space as key
   ['SRCPARAM', '1', '6.35e-07', '15.00340.00', '1.103.0']

   def getElements( str ):
   return str.replace( '  ', '' ).strip().split(' ')


sph

--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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

Re: alternative to eclipse [ python ide AND cvs ]

2007-05-18 Thread Steven Howe
Stargaming wrote:
> yomgui schrieb:
>   
> Hi,
>
> Eclipse is just not really working on linux 64 bit
> (I tried ubuntu and centos, it is freesing and crashing
> and extremly slow)
>
> I use eclipse for python and cvs, what is "the" good alternative ?
>
> thanks
>
> yomgui
>   

Fond of Komodo. Seems to run most of my python programming tasks. Has 
breakpoints/debugging, introspection, projects and the professional 
version supports CVS.  The only issue I have is that they 
(ActiveState.com) just raised the price of the personal IDE way too 
high. I'll be using my older version (3.1) for a while. If I used it at 
work, I'd certainly have my boss splurge the 200 odd dollar price. But, 
in their favor, they have a editor version for free. I 'think' it 
doesn't have the damn fine debugging or CVS feature though.

sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: remove all elements in a list with a particular value

2007-05-18 Thread Steven Howe
Steven Howe wrote:
> MRAB wrote:
>> On May 16, 4:21 pm, Lisa <[EMAIL PROTECTED]> <mailto:[EMAIL PROTECTED]> 
>> wrote:
>>   
>> I am reading in data from a text file.  I want to enter each value on
>> the line into a list and retain the order of the elements.  The number
>> of elements and spacing between them varies, but a typical line looks
>> like:
>>
>> '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10  3.0   '
>>   
> Using builtin functions:
>
> ax = '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10  3.0   '
> >>> ax.replace('  ','')  # replace all double spaces with nothing
> ' SRCPARAM 1 6.35e-07 15.00340.00 1.103.0 '
> >>> ax.replace('  ','').strip() # strip leading/trailing white spaces
> 'SRCPARAM 1 6.35e-07 15.00340.00 1.103.0'
> >>> ax.replace('  ','').strip().split(' ') # split string into a
> list, using remaining white space as key
> ['SRCPARAM', '1', '6.35e-07', '15.00340.00', '1.103.0']
>
> def getElements( str ):
> return str.replace( '  ', '' ).strip().split(' ')
>
>
> sph
>
Made a mistake in the above code. Works well so long as there are no 
double spaces in the initial string.
Try 2:
def compact( y ):
if y.find('  ') == -1:
 return y
else:
y = y.replace( '  ', ' ' )
return compact( y )

 >>> ax = '   acicd  1.345   aex  a;dae'
 >>> print compact( ax )
 acicd 1.345 aex a;dae
 >>> print compact( ax ).strip().split()
['acicd', '1.345', 'aex', 'a;dae']

sph

> -- 
> HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
>   


-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

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


Re: How can i compare a string which is non null and empty

2007-04-02 Thread Steven Howe
how about just testing it's length?
 >>> from types import StringType

def stringTest(x):
... if type(x) == StringType:
... if len(x) == 0:
... print 'Empty String'
... else:
... print 'Not Empty String'
... else:
... print 'value not String Type'
...
 lst = ['a','',5,(5,6),{'a':5}]
for item in lst:
... stringTest(item)
...
Not Empty String
Empty String
value not String Type
value not String Type
value not String Type

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


Re: how can I clear a dictionary in python

2007-04-04 Thread Steven Howe
Tempest in a teapot guys.

Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Antoon Pardon  <[EMAIL PROTECTED]> wrote:
>   
>> On 2007-04-03, Aahz <[EMAIL PROTECTED]> wrote:
>> 
>>> In article <[EMAIL PROTECTED]>,
>>> Larry Bates  <[EMAIL PROTECTED]> wrote:
>>>   
 Aahz wrote:
 
> In article <[EMAIL PROTECTED]>,
> Larry Bates  <[EMAIL PROTECTED]> wrote:
>   
>> [EMAIL PROTECTED] wrote:
>> 
>>> I create a dictionary like this
>>> myDict = {}
>>>
>>> and I add entry like this:
>>> myDict['a'] = 1
>>> but how can I empty the whole dictionary?
>>>   
>> just point myDict to an empty dictionary again
>>
>> myDict={}
>> 
> Go back and read Christian's post, then post a followup explaning why his
> solution is better than yours.  Your explanation should use id().
>   
 I believe he (as many new to Python do) are mired in old programming
 thinking that variables "contain" things.  As I'm sure you kno,
 variables point to things in Python.  I don't believe that there are
 lots of other objects pointing to this dictionary.  Perhaps the OP
 can clarify for us.  If there aren't other objects pointing to this
 dictionary it would make NO sense to iterate over a dictionary and
 delete all the keys/values so I tried to read between the lines and
 answer what I believe the OP thought he was asking.
 
>>> Then you should explain why you didn't answer the question that was
>>> asked.  Answering a different question without explanation makes your
>>> answer irrelevant at best, wrong at worst.
>>>   
>> This is not true. If this different question was in fact the intended
>> question instead of the one actually asked. Anwering this different
>> question can be more usefull than answering the one actually asked.
>> 
>
> Note carefully that I did not say, "Don't answer the question you think
> should have been asked."  What I said was, "If you answer a different
> question, EXPLAIN WHY."  Is that so difficult to understand?
>   

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


Re: Why NOT only one class per file?

2007-04-05 Thread Steven Howe
Dennis Lee Bieber wrote:
> On 4 Apr 2007 14:23:19 -0700, "Chris Lasher" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>   
>> A friend of mine with a programming background in Java and Perl places
>> each class in its own separate file in . I informed him that keeping
>> all related classes together in a single file is more in the Python
>> idiom than one file per class. He asked why, and frankly, his valid
>> question has me flummoxed.
>>
>> 
>   As I recall, Java essentially doesn't offer a CHOICE... So I'd
> consider any argument that "one per file" is best to be flawed if based
> upon Java practice. After all, if one can not even experiment with other
> ways, how can one really evaluate the options? {and I consign Perl to
> realms described by Dante}
>   
On class per file was easier to do when Java was developed (remember it 
was develop to control
vending machines; scary. Reminds me of the movie 'Tron'). The desktop 
computer for Sun 
was an IPC workstation.  Nice but no balls and no good editors that 
could have 24+ tabs open or
 a way to 'close' sections of coherent text (which are common in my 
preferred editor, Komodo).

So your friend is arguing the past. Ask him if he's a Republican too or 
needs a serious reboot.
I have a good pair of boot to give him a kick in the ass (Democrats 
would need a kick in the head
to reset; we all know what organ Republican think with).
sph


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


Re: Can we make a local variable in a function as global variable???

2007-04-05 Thread Steven Howe

sairam wrote:

I have some local variables defined in one method and Can I make those
variables as global variables? If so , can any one explain me how can
I do that


Thanks,
Sairam

  

See: http://www.faqs.org/docs/diveintopython/dialect_locals.html

When a line of code asks for the value of a variable x, Python will 
search for that variable in all the available namespaces, in order:


  1. local namespace - specific to the current function or class
 method. If the function defines a local variable x, or has an
 argument x, Python will use this and stop searching.
  2. global namespace - specific to the current module. If the module
 has defined a variable, function, or class called x, Python will
 use that and stop searching.
  3. built-in namespace - global to all modules. As a last resort,
 Python will assume that x is the name of built-in function or
 variable.

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

Re: Why NOT only one class per file?

2007-04-05 Thread Steven Howe
Now we're at the '_/How many Angels can dance on the head of a pin/_' 
question (like anything with wings would waste time dancing. Ever seen 
eagles mate (not the football players)? Dance it's not, but it looks 
like /sex on a roller coaster only better/! Get me a pair of wings!).  
Religious war over please! They get me long winded (as you'll note if 
you keep reading).  So, back to the original questions, now long forgotten.


The questions (there were three) were:
(1) Why does Java require each class be in a separate file?
(2) Why Python has no such rule?
And
(3) Is there a reason I should do one or the other (I assume that means 
either, (3)(a) one class per file, regardless of language and/or (3)(b) 
Java or Python).


--  
--

Answers:
Question (1):

   There appear to be four answers to this question.
   (a) Don't know (most answers, but with some religious dogma
   attached. JAVA bad; PYTHON good and I worship PHP. Move the adj.
   around  to suit your tastes).

   (b) KISS principle. /Keep It Simple, Stupid/. This is probably the
   right answer. Back then SUN, or as some of us remember '/Stanford
   University Network/' employed some sharp people (I must admit, my
   main reason for disliking SUN and CISCO was where they started. I
   was from UC Berkeley. It should have been UCBUN, or Uncle Buns; but
   that's just wouldn't sell. See how well BSD or 'bastard' sells).

   (c) Early Java development technology not up to n+1 classes in a
   single file. Reasonable from an old programmer's point of view.
   Those old IPC workstation didn't have that much memory. Small
   compiling jobs and executable loads would have been preferred if not
   required. I remember my first IPC had 4 Megabytes of RAM (boy did I
   have to beg for that box!) My Compaq 386/20 MHz computer, running
   MSDOS 3.1 only had 1 Meg and a Hercules graphics card (16 colors. I
   must have been good that year). I must have been a star, as most
   other's new hires were using '*/Bleeding Edge/*' computers (and if
   you don't know the reference, your just too young; think Gateway or
   Dell's cheap, hobbled products). File and more importantly, virus
   transfers where by /SneakerNet/. You young people have it too good;
   just one message via Exchange and you can infect a million computers
   in a thousand countries in moments. We had to work at it before we
   could take a day off as IT reloaded our computers. Thank God or Bill
   Gates, that companies keep buying a broken product.

   (d) Last. It was developed for vending machines (as someone pointed
   out, it started life as 'OAK'). Small memory foot print and a
   limited feature set were no brainers. '/We Taka the coins in, We
   dropa the Twinky out'. /The net's early domination by Unix variants
   and the Macintosh made Java's '/jack of all trades'/ a good
   solution. It was the main reason Microsoft tried (and failed) to
   '/Embrace and Extend'/ Java (Novell watch your ass; Microsoft wants
   to embrace and extend up your backside. SUN, just like a good
   Catholic girl said NO! (Or not in public! as the IBM/SCO trial seems
   to show)).

   So, pick an answers. It's God's fault/feature (sorry, I forget SUN
   != Microsoft), a programming dogma, hardware related or just old
   fashion growing pains. Probably some of each is the truth.


Question (2):

   Python is a later generation language then Java. Without a SUN,
   Digital or Microsoft to push it, it had to serve it's users better.
   Design limitations, due to hardware (see HP and Korn shell) weren't
   a consideration. The main issue I could see, when I was first
   introduced to the Python language, was the reduction of overhead and
   limited ways of doing the same task (1/ Perl ^ n in my experience).
   The need to prettify code so other could read it, or more
   importantly, so other's couldn't read it (for job security), wasn't
   there. Python really is easy to learn, like Pascal was suppose to be.

   Python, like Java was OO from the word go (ok gcc for you purists),
   but was not syntactically  a descendant of C++, so non-C++
   programmers didn't need to pay homage to AT&T (and God's only son,
   Bell Labs, from whence the Holy Ghost, Unix was created, destroyed
   and reborn as BSD. Is there a movie with Mell Gibson there?
   Remember, I said it first!).

   Freedom of vendors often means best of breed wins (i.e. most useful
   feature are includes). Freedom of vendors also means it hard to get
   into your shop (no one ever got fired for buying IBM after all).

That takes care of why, I hope. _No doubt_ there's a few opinions left 
to be expressed. Who knows, they might stay on topic as well or better 
them I.


Question (3):

   (3)(a) Is there a reason I should practice the 'One Class per File'
   rule?
   Answer is *yes,* when it makes your programming task easier and
   *no,* when it makes your progr

Re: how to strip the domain name in python?

2007-04-15 Thread Steven Howe




[EMAIL PROTECTED] wrote:

  On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
  
  
On Apr 14, 12:02 am, Michael Bentley <[EMAIL PROTECTED]>
wrote:





  On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:
  


  
Hi,

  


  
I have a list of url names like this, and I am trying to strip out the
domain name using the following code:

  


  
http://www.cnn.com
www.yahoo.com
http://www.ebay.co.uk

  


  
pattern = re.compile("http:(.*)\.(.*)", re.S)
match = re.findall(pattern, line)

  


  
if (match):
s1, s2 = match[0]

  


  
print s2

  


  
but none of the site matched, can you please tell me what am i
missing?

  


  change re.compile("http:(.*)\.(.*)", re.S) to re.compile("http:\/
\/(.*)\.(.*)", re.S)
  

Thanks. I try this:

but when the 'line' ishttp://www.cnn.com, I get 's2' com,
but i want 'cnn.com' (everything after the first '.'), how can I do
that?

pattern = re.compile("http:\/\/(.*)\.(.*)", re.S)

match = re.findall(pattern, line)

if (match):

s1, s2 = match[0]

print s2

  
  
Can anyone please help me with my problem?  I still can't solve it.

Basically, I want to strip out the text after the first '.' in url
address:

http://www.cnn.com -> cnn.com

  

Generalized, you'll want to add some 'try' test to verify the not
returning just root domains ('com', 'edu', 'net' etc)

Start with spliting?
from string import split, find
url=''
url.split('//')
['http:', 'www.cnn.com']

site = url.split('//')[1:][0]
site ='www.cnn.com'

site.find('.')
3
site[site.find('.')+1:]
'cnn.com'
domain = site[site.find('.')+1:]

from string import split, find
def getDomain( url=''):
    site = url.split('//')[1:][0]
    domain = site[site.find('.')+1:]
    return domain



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

Re: Newbie: import

2007-04-18 Thread Steven Howe

[EMAIL PROTECTED] wrote:

I thought import used relative paths from either the python executable
or the script being executed.  I have a script pulling in code from an
arbitrary directory.  How is this happening?

It's a RHEL 4 environment by the way.  I couldn't find any relevant
environment variables.

Thanks from a newbie for any insight.

  

See 

   http://docs.python.org/tut/node8.html#SECTION00811


   6.1.1 The Module Search Path

   When a module named spam is imported, the interpreter searches for a
   file named spam.py in the current directory, and then in the list of
   directories specified by the environment variable PYTHONPATH. This
   has the same syntax as the shell variable PATH, that is, a list of
   directory names. When PYTHONPATH is not set, or when the file is not
   found there, the search continues in an installation-dependent
   default path; on Unix, this is usually .:/usr/local/lib/python.

   Actually, modules are searched in the list of directories given by
   the variable |sys.path| which is initialized from the directory
   containing the input script (or the current directory), PYTHONPATH
   and the installation-dependent default. This allows Python programs
   that know what they're doing to modify or replace the module search
   path. Note that because the directory containing the script being
   run is on the search path, it is important that the script not have
   the same name as a standard module, or Python will attempt to load
   the script as a module when that module is imported. This will
   generally be an error. See section 6.2
   , ``Standard
   Modules,'' for more information.

Then try

   import sys
   sys.path


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

Re: % sign in python?

2008-07-17 Thread Steven Howe

Terry Reedy wrote:



korean_dave wrote:

What does this operator do? Specifically in this context

test.log( "[[Log level %d: %s]]" % ( level, msg ), description )

(Tried googling and searching, but the "%" gets interpreted as an
operation and distorts the search results)


Having seen a number of comments like this over the years (about the 
difficulty of searching for symbol meanings), I just started, last 
night, a symbol index listing nearly all Python syntax uses of 
non-alpha-or-digit ascii symbols.  When I finish and upload it 
somewhere, I will post an announcement with the link.


tjr

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


I thought, in this contexted, it was  mapping operator.
sph
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to duplicate array entries

2010-01-11 Thread Steven Howe

try
---
#!/usr/bin/env python
from types import ListType, IntType

def array_expander( ar=None, ex=None ):
if type( ex ) != IntType:
return []
if ex <= 0:
return []
if type( ar ) != ListType:
return []
# working code starts here #
res = []
for t in ar:
for x in range( ex ):
res.append( t )
return res
# function ends #

res = array_expander( [1,11,3,5], 4 )

print res
---
[1, 1, 1, 1, 11, 11, 11, 11, 3, 3, 3, 3, 5, 5, 5, 5]



--
*Kiri-kin-tha's* First Law of Metaphysics is /"Nothing unreal exists."/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with a program

2010-01-28 Thread Steven Howe

On 01/28/2010 09:49 AM, Jean-Michel Pichavant wrote:

evilweasel wrote:

I will make my question a little more clearer. I have close to 60,000
lines of the data similar to the one I posted. There are various
numbers next to the sequence (this is basically the number of times
the sequence has been found in a particular sample). So, I would need
to ignore the ones containing '0' and write all other sequences
(excluding the number, since it is trivial) in a new text file, in the
following format:


seq59902

TTTATTATATAGT


seq59903

TTTATTTCTTGGCGTTGT


seq59904

TTTGGTTGCCCTGCGTGG


seq59905

TTTGTTTATGGG

The number next to 'seq' is the line number of the sequence. When I
run the above program, what I expect is an output file that is similar
to the above output but with the ones containing '0' ignored. But, I
am getting all the sequences printed in the file.

Kindly excuse the 'newbieness' of the program. :) I am hoping to
improve in the next few months. Thanks to all those who replied. I
really appreciate it. :)
Using regexp may increase readability (if you are familiar with it). 
What about


import re

output = open("sequences1.txt", 'w')

for index, line in enumerate(open(sys.argv[1], 'r')):
   match = re.match('(?P[GATC]+)\s+1')
   if match:
   output.write('seq%s\n%s\n' % (index, match.group('sequence')))


Jean-Michel


Finally!

After ready 8 or 9 messages about find a line ending with '1', someone 
suggests Regex.

It was my first thought.

Steven

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


Re: Personal criticisms and logical fallacies

2010-02-09 Thread Steven Howe
Really, is this a relevant topic on a program mail list? You guys need 
to get a room and start discussing angel counts on pinheads under the 
blankets.


sph

On 02/09/2010 10:51 PM, D'Arcy J.M. Cain wrote:

On Wed, 10 Feb 2010 01:38:50 +0100
"Alf P. Steinbach"  wrote:
   

However, although in this particular case the Ad Hominems constituted logical
fallacies, not all Ad Hominems are logical fallacies.
 

Yes they are.  Using the reputation of someone to prove or disprove
their claims is a logical fallacy.

   

For example, if a person is a chronic liar, has a known history of lying, then
that can have a strong bearing on whether the person's claims  --  technical or
about other persons  --  should be seriously considered[1].
 

Yes but it's still a fallacy.  Taking the author's history into account
may be valid for deciding that further investigation is warranted but by
itself it does not prove anything about the claims.  Suggesting that it
does is fallacious.

"Bill is a liar therefore his statement is false" is a fallacy.  "Bill
is a liar so take his claims with a grain of salt" is not.

There is another case.  "Bill never tells the truth therefore his
claim is wrong" is not an ad hominem fallacy.  It's a sylogism.  It may
or may not be correct but if the first statement is true (Bill always
lies) then the the conclusion is true.

   


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


Re: Python Opportunity at OPNET

2010-03-04 Thread Steven Howe

On 03/04/2010 04:45 PM, Harold Meder wrote:
I stumbled across this Job Posting 
 at 
OPNET.
I hope that it is acceptable to post this type of info on this mailing 
list.

I do not know any further information regarding this opportunity.

   Harold Meder.

Harold,
Thats just a net looking to scoop up people. There's no job there. Just 
a staffing house looking for resumes in expectation for the job market 
to pickup. Staffing houses rip tech people off.


sph




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


Re: compiler with python

2010-03-06 Thread Steven Howe
Is it possible he's talking about a 'quad core'? as in a CPU? In that 
case I think he wants

to optimize a python program for a multiprocessor core with four processors.

sph


On 03/06/2010 07:56 AM, Dave Angel wrote:

mohamed issolah wrote:


2010/3/6 Dave Angel 


mohamed issolah wrote:


hey,

How can I construct a compiler with python just for informatiom ., 
I have

habit to construct it with C language,

sorry for my english ;-)



You need to tell us what you're really trying to do, what tools you're
willing to use, and probably why you want it.  And if you're not 
sure about

your English, keep the sentence structure straightforward.

Let me make a couple of wild guesses:




You want to design and build a compiler that takes xml information 
as its
source code, and compiles those xml files into Intel x86 machine 
code.  The
compiler and the resulting executable needs to run on an x86 Linux 
machine.
 Your previous experience was in doing this sort of thing in C, but 
you want
to try it with Python instead.  You want to do it without using the 
lxml

libraries.

You want to build a python compiler, that takes python source code and
produces Java byte code files.  You'd like to do this in C, but 
don't want
to use any of the available existing CPython or Jython source code.  
Your
goal is not to make a commercially viable product, but to learn as 
much as

possible in the process.


DaveA



hey,

I want to create a compiler which transform a code like pascal code 
(that

what I do in C) to "quad"
In C, I use BISON and FLEX tools.


I've forwarded your message to the list, and fixed your top-posting by 
moving your response to the bottom.  I don't have a clue what "quad" 
is, unless it's a synonym for Forth.


You haven't specified the OS you'll be using to run the compiler, nor 
the one you're targeting, so some of these choices may not be useful.  
For example, the first one is Linux only.


http://www.freenet.org.nz/python/pybison/
PyBison - Python binding for Bison/Flex

http://freshmeat.net/projects/yeanpypa/
http://www.slash-me.net/dev/snippets/yeanpypa/documentation.html

http://www.python.org/community/sigs/retired/parser-sig/towards-standard/

Or you could go here, which has links to (most of) these and others.
http://wiki.python.org/moin/LanguageParsing

DaveA

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


Re: File existence check with partial filename

2010-03-15 Thread Steven Howe

What wrong with glob?
---
Help on module glob:

NAME
glob - Filename globbing utility.

FILE
/usr/lib64/python2.6/glob.py

FUNCTIONS
glob(pathname)
Return a list of paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la fnmatch.

iglob(pathname)
Return an iterator which yields the paths matching a pathname 
pattern.


The pattern may contain simple shell-style wildcards a la fnmatch.

DATA
__all__ = ['glob', 'iglob']

---
solution:

import glob

for afile in glob.iglob( "/home/buddy/*.HV" ):
print afile


sph


On 03/15/2010 08:44 AM, MRAB wrote:

Lan Qing wrote:

Or use the regular module:

import re
import os

for filename in os.listdir('.'):
if re.match("*HV*", filename):
  # do something with the file


The regular expression should be ".*HV.*", although:

re.search("HV", filename)

would be better and:

"HV" in filename.upper()

would be even better, as Alf posted.

On Mon, Mar 15, 2010 at 12:24 PM, Alf P. Steinbach > wrote:


* Sang-Ho Yun:

I learned that I can check the existence of a file using
os.path.isfile("filename").

What if I need to check if there is a file that contains "HV" 
in the

filename?  What should I do?



   from __future__ import print_function
   import os

   for filename in os.listdir( "." ):
   if "HV" in filename.upper():
   print( filename )



Cheers & hth.,

- Alf

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






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


Re: CPAN for python?

2010-03-30 Thread Steven Howe
This question comes up at least once a month, eliciting a thread that 
goes on for day.
Wouldn't it be wise to put a link on the bottom of the mail list? 
Something like


CPAN for Python == PyPi << make that an href

or

Python( CPAN ) = PyPi

Not too many characters.

sph


On 03/30/2010 09:23 AM, Someone Something wrote:

Hi,
I've learned python a few months ago but I still use Perl because of 
CPAN and the tremendous amount of stuff that's already been done for 
you. is there something like CPAN for python?


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


Re: Style question for conditional execution

2010-11-24 Thread Steven Howe
Both paradigms are in the bash shell. Using a test switch (like -x for 
executiable) mixed with an && or ||.

Example:
[-x /usr/bin/firefox ] || exit

I think it's very clear, to old hands, but not so much for a new or
intermediate users.

It certainly is the 'cleaner' form. Like the C style increment " x++ " 
or the insidious  " x += 4 ". However I often found myself looking for 
places to use "x += 4" instead of just using the clear:

"x = x + 4 ".

Unless there is a significant compiler/executable improvement it just 
there to amuse yourself.


The
if v:
f()

structure is clearer. Which is the only reason to use indents, braces 
and the like. I suppose that's my vote/opinion. Given a choice between 
clean or clear, take clear.


sph


On 11/24/2010 10:46 AM, Gerald Britton wrote:

Writing in Python gives me the luxury of choosing different paradigms
for similar operations.  Lately I've been thinking about a minor
detail that peaked my interest and am curious what others think:

Say that I have some function "f" that I will execute if some variable
"v" evaluates true.  Using a classical procedural approach, I might
write:

 if v:
 f()

I might, however, think more in a functional-programming direction.
Then I might write:

 v and f()

Interestingly, this second expression compiles smaller (though only by
a little) in both Python 2.6 and 3.1, which I currently have
installed.  If I had thousands of such expressions, I could boast
about a measurable difference but practically speaking, it is not
significant.

What I _am_ interested in, however, is feedback from a style perspective.

What do the rest of you think about this?

Have you used the second approach and, if so, what was your motivation?

Is there a good/bad reason to choose one over the other?



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


Re: Code review request

2010-12-22 Thread Steven Howe

On 12/22/2010 10:34 AM, Jason Staudenmayer wrote:

Hi All,
I'm a python newbie so please be kind. I've been reading book after book and have written 
a script or two but this is my first real "program". Just looking for any 
suggestions and pointers. I've done some work with bash scripts and php (not OOP) a while 
a go. I'm not a programmer but would like to possibly expand in to it (right now an IT 
guy). Am I on the right track so far?

The program should be documented enough to explain.

"""
Created on Tue Dec 21 13:39:41 2010
@author: jason

Usage: cmd_drug_testing.py [options]...
Will select a random employee from the local database (located in the current 
directory)
and display the name by default.

This program (Drug Testing) was written to help select employees for drug 
testing.
Program usage:

 -h, --help   Displays this help info
 -l, --list-emplysLists all employees in the database
 -s, --select Select employee for testing
 -r, --remove-emply   Delete employee from database, usage: -d 
employee_name or id
 -e, --edit-emply Edit employee data in database, usage: -e 
employee_name or id
field_to_change new_value
 -i, --insert-emply   Insert new employee in database:
 must fit this format -- "id:or '','lastname, 
firstname', 'email',0"
 -f   Display database name and full path

This program was written by, Jason S. For the use of AA.

"""

# import our needed modules
import sqlite3 as sqlite
import sys, getopt

#set global vars
global cursor
global conn


def usage():
 """ this just prints the usage in the doc string"""
 print __doc__

def dbconnect(sql):
 """handel the connction to the sqlite db  """
 dbConnection = sqlite.connect("drug-test.db")
 #set the cursor
 cursor = dbConnection.cursor()
 try:
 #execute the sql passed from the other funtions and return the results
 result = cursor.execute(sql)
 dbConnection.commit()
 except sqlite.Error, e:
 result = e.args[0]

 return result


def listEmployees(sql):
 #list all records in the database
 listemp = dbconnect(sql)
 for lst in listemp:
 print "%s, %s, %s, %s" % (lst[0],lst[1],lst[2],lst[3])

def selectOneEmployee(sql):
 #select a random record from the database
 listemp = dbconnect(sql)
 for empl in listemp:
 print empl[0]

def removeOneEmployee(sqlchk,sqldel):
 #delete one employee by ID number
 chk = dbconnect(sqlchk)

 if chk.fetchone() != None:
 #check to make sure the ID is valid in the database
 emply = dbconnect(sqlchk)
 emply = emply.fetchall()
 print "trying to remove employee %s" % (emply)
 try:
 dbconnect(sqldel)

 except sqlite.Error, e:
 result = e.args[0]
 print result

 else:
 print "Employees ID is invalid, please check the ID number"

def insertEmployee(sql):
 #insert a new employee into the database
 print sql
 try:
 dbconnect(sql)

 except sqlite.Error, e:
 result = e.args[0]
 print result

def main(argv):
 """The purpose of this program is to select an empployee from this 
database for random drug
 testing. This program can also perform maintainance on same database."""
 if argv == []:
 sql = "SELECT name FROM employees ORDER BY RANDOM() LIMIT 1;"
 print "The following employee has been selected\n"
 selectOneEmployee(sql)

 try:
 #get the options passed by the user
 opts, args = getopt.getopt(argv, 
"hlsr:e:i:d",["Help","list-emplys","select","remove-emply=","edit-emply=","insert-emply="])

 except getopt.GetoptError:
 usage()
 sys.exit(2)

 #check throught the options and respond accordingly
 for opt, arg in opts:
 if opt in ("-h", "--help"):
 usage()
 sys.exit()
 elif opt == '-d':
 global _debug
 _debug = 1
 elif opt in ("-l", "--list-emplys"):
 sql = "select * from employees"
 listEmployees(sql)
 elif opt in ("-s","--select"):
 sql = "SELECT name FROM employees ORDER BY RANDOM() LIMIT 1;"
 print "The following employee has been selected\n"
 selectOneEmployee(sql)
 elif opt in ("-r","--remove-emply"):
 if arg == "":

 sys.exit("You must provice the ID for the employee to remove")
 sqlchk = "select * from employees where id = \"%s\"" % (arg)
 sqldel = "delete from employees where id = \"%s\""  % (arg)
 removeOneEmployee(sqlchk,sqldel)
 elif opt in ("-i", "--insert-emply"):
 sql = "insert into employees values(%s)" % (arg)
 insertEmployee(sql)

if __name__ == "__main__":
 main(sys.argv[1:

Re: Is it possible to let a virtual file created by cStringIO have a filename so that functions can read it by its filename?

2011-01-14 Thread Steven Howe

On 01/14/2011 12:51 PM, Chris Rebert wrote:

On Fri, Jan 14, 2011 at 7:52 AM, Cun Zhang  wrote:

Hi,all
I hope use cStringIO to create virtual file, but my customed function which
is from a shared library imported by ctypes
just accepts a filename(string type) as parameter.

So I'm wondering whether there is any method that make the virtual file
created by cStringIO like a normal file which have
a filename, so it can be called by my functions.

That's not possible. (c)StringIO presents a file-like interface at the
Python level, but under the covers, it's not implemented using
anything like a normal file; thus, it doesn't have a presence on any
filesystem. I would suggest using a temporary file
(http://docs.python.org/library/tempfile.html ) for communicating with
the C module, writing the contents of the StringIO object to the
temporary file if necessary.
(It's probably also possible to hack something together with FUSE, but
it'd be a slow, platform-specific kludge.)

Cheers,
Chris
--
http://blog.rebertia.com


However, as the only reason to have the cstringIO object have a name is
for you to open or close it. The rest of the functionality is the same, 
reading and writing too.



--
in a terminal ...
import cStringIO

ab = cStringIO.StringIO() # an output type, as it was call with nothing.
cd = cStringIO.StringIO( 'a filled buffer') # an input type.

type( ab ) == cStringIO.OutputType
True

type( cd ) == cStringIO.InputType
True

Working with these properties  we get


Let's assume you have class with read and write ability,
which assumes opening a file or cStringIO object (could
extend to StringIO object with out much changing ).


class foo:
def __init__( self ):
""" Define some variables. House keeping. """
self.readState = False
self.writeState = False
self.readObj = None
self.writeObj = None

def fooOpenWrite( self, fileobj ):
if type( fileobj ) === StringType:
self.writeObj = open( fileobj, 'wb' )
elif type( fileobj ) == cStringIO.OutputType:
self.writeObj = fileobj
else:
self.writeState = False
return
self.readState = True
return True

def fooOpenRead( self, fileobj ):
if type( fileobj ) === StringType:
self.readObj = open( fileobj, 'wb' )
elif type( fileobj ) == cStringIO.OutputType:
self.readObj = fileobj
else:
self.readState = False
return
self.readState = True
return

def fooRead( self ):
for x in self.readObj:
print x

def fooWrite( self, str ):
self.readObj.write( str )


Steven

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


Re: Tkinter: Joking?

2011-01-17 Thread Steven Howe

On 01/16/2011 10:46 PM, Octavian Rasnita wrote:

From: "Steven D'Aprano" 
Sent: Monday, January 17, 2011 1:04 AM
Subject: Re: Tkinter: The good, the bad, and the ugly!


Well, true, but people tend to *use* the parts of the GUIs that are
simple and basic. Not only do the big complicated apps get all the press
even when they are actually a niche product (everyone knows about
Photoshop, but more people use MS Paint) but it's a truism that most
people use something like 20% of the functionality of big, complicated
GUI apps. Most people use Microsoft Word or OpenOffice for little more
than text editing with formatting.




True, but the most important thing is that those apps need to work and 
these days the portability of programs is also important for making 
them available to as many people as possible.


wxWIDGETS are portable and also pretty accessible for those who need 
to use screen readers which is not the case of purely native widgets 
as the Win32 GUI standard controls or the libraries like Tk, GTK or QT.


Octavian

If you are making a product, you want it to be unique and inaccessible 
to other companies/products. Hence 'propriety'. It's part of that 
'capture the market' mindset that engineers and programmers have a 
problem with. Fight or flight, you have to deal with it.


So ...

Target your market. Design your software in the Model-View-Controller 
format. It becomes easy to configure you frontend, your GUI, your web 
page, if your code is written to separate the work from the glitz.


Car companies know this. There is the body design crew, and the 
engineers that make it work. So software products too. Artists always 
come first; with good reason, their work catches the eye; remember what 
Dr. Lecter said "Don't your eyes seek out what you want Clares?". 
Fighting that fact, for 'efficiency' is just tilting at windmills (or 
Pontiac Aztec).


Instead, think 'optimal' i.e. maximum usage per market. MVC makes that 
approach reasonable in the first market. Easy in the second (Apple), 
third (Linux) and fourth (BSD).


In the mean time, quit bad mouthing works like Tk/Tcl that have come 
before the current crop. Their successors too shall pass.


Oh, and if your interested, I'm in the third market, been here since 
1992. Time and Tide Microsoft, Apple. Time and tide.


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


Re: How to open and read an unknown extension file

2010-04-08 Thread Steven Howe

On 04/08/2010 08:57 AM, Chris Colbert wrote:

On Thu, Apr 8, 2010 at 11:42 AM, Kushal Kumaran
  wrote:
   

On Thu, Apr 8, 2010 at 9:00 PM, varnikat t  wrote:
 

I am trying to do this
if os.path.exists("*.*.txt"):
 file=open("*.*.txt")
 self.text_view.get_buffer().set_text(file.read())
else:
 file=open("*.*.html")
 self.text_view.get_buffer().set_text(file.read())

It gives error *.*.txt not existingThere are two files in the folder
testing.pnm.txt
and testing.pnm.html
How to make it open any name and extension file and read it?

   

os.path.exists does not do pattern matching like that.  Take a look at
the glob module.

--
regards,
kushal
--
http://mail.python.org/mailman/listinfo/python-list

 

In [4]: files = [f for f in os.listdir(os.getcwd()) if
os.path.splitext(f)[-1]=='.txt']

In [5]: files
Out[5]:
['pip-log.txt',
  'extended_abstract.txt',
  'testlog.txt',
  'pymazon_error_log.txt',
  'hny.txt']
   

seems like a lot of work

from glob import glob

mylist = glob( "*.txt" )
for item in mylist:
print item

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


Re: Merge two directories together

2010-04-16 Thread Steven Howe

Think about using the subprocess module. There are calls made just for
your. Notably (using command pydoc subprrocess.call) :
-
subprocess.call = call(*popenargs, **kwargs)
Run command with arguments.  Wait for command to complete, then
return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])
-----


Steven Howe


On 04/16/2010 06:48 AM, Keith Hughitt wrote:

Suppose you have two file-trees with common sub-directories but
different files that you want to merge together, e.g.

/test/
/test/a/
/test/a/file1

/test2/
/test2/a/
/test2/a/file2

You can easily merge the directories in Linux using the "cp" command:

cp -r test/* test2/

While Python provides some helpful methods for moving files and
directories around (shutil.move, shutil.copytree, etc), none of them
seem to be able to merge two directories.

I've looked around some on Google for an alternative to calling cp
directly, but so far no luck.

Any ideas?
   


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


Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Steven Howe

Really! Learn to use google better. I just used "python sort list"

Look at: http://wiki.python.org/moin/HowTo/Sorting

Read about list.sort. Try, at a command prompt (assuming you have a unix 
shell), "pydoc list"

search for sort; read it. It mentions 'reverse'.

then slice the list to your desired set and return.

sph


On 04/23/2010 07:02 AM, Grant Edwards wrote:

On 2010-04-22, D'Arcy J.M. Cain  wrote:
   

On Thu, 22 Apr 2010 15:04:01 +0100
Tim Golden  wrote:
 

So please tell me if there is one or not. I really need this soon.
Appreciate a lot.
 

Assuming top-k doesn't mean something obscurely statistical:
   

You really shouldn't do people's homework for them.  It doesn't do
them any favours.
 

Doing people's homework for them is a survival mechanism -- it reduces
the competence of potential new rivals.  :)

OTOH, if you do end up working with one of those a new grads with a
diploma but not a clue, you end up worse off because now you have to
teach them the problem solving skills they didn't learn in school.

   


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


Uses of a deprecated module 'string'

2010-06-22 Thread Steven Howe

Hi, I'm trying to import 'letters' from the string module.
I get the following message:

Uses of a deprecated module 'string'

I realize the functionality of 'string' is now in the _builtin_. But are the
constants. If so, what are they called. I tried 'letters', but got:

NameError: name 'letters' is not defined

Thanks for any help.

Steven Howe

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


Re: Opposite of split

2010-08-15 Thread Steven Howe

 On 08/15/2010 11:35 AM, Gary Herron wrote:

On 08/15/2010 11:24 AM, Alex van der Spek wrote:
Looking for a method that does the opposite of 'split', i.e. elements 
in a list are automatically concatenated with a user selectable 
spacer in between e.g. '\t'. This is to prepare lines to be written 
to a sequential file by 'write'.


All hints welcome.

Regards,
Alex van der Spek


Strings have a join method for this:
'\t'.join(someList)

Gary Herron

or maybe:
-
res = ""
for item in myList:
res = "%s\t%s" %  ( res, item )

myList = ["abc","def","hjk"]
res = ""
for item in myList:
res = "%s\t%s" % ( res, item )
res
'\tabc\tdef\thjk'


print res
abcdefhjk

Note the leading tab.
-
So:
>>> res.strip()
'abc\tdef\thjk'
>>> print res.strip()
abcdefhjk

simple enough. Strange you had to ask.

sph

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