Re: Problem with calling function from dll

2012-12-13 Thread Ulrich Eckhardt

Am 13.12.2012 08:40, schrieb deep...@poczta.fm:

I have problem with using function from dll.

import ctypes

b = ctypes.windll.LoadLibrary("kernel32")

a = ""

b.GetComputerNameA(a,20)


GetComputerNameA takes a pointer to a writable char string. You give it 
a pointer to an immutable string. You will have to create a buffer first 
and pass that to the function. Also, I would use GetComputerNameW 
instead, although it makes little difference for this name (provided 
that's the hostname, which may only contain an ASCII subset).




But I got exception:

Traceback (most recent call last):
   File "", line 1, in 
 b.GetComputerNameA(a,20)
WindowsError: exception: access violation reading 0x0014


Here is something else that is wrong: The address 0x0014 that the 
function tries to access is neither the address of a mutable nor an 
immutable string but simply the value 20 that you passed as second 
parameter. In other words, the way that the parameters are passed to the 
function is wrong.




Even when I write:
a = ctypes.c_char_p('.' * 20)
I got the same result.


This looks much better than passing the string above, but it still seems 
the (hopefully correct) parameters are passed wrongly.



Here I found this function description:
http://sd2cx1.webring.org/l/rd?ring=pbring;id=15;url=http%3A%2F%2Fwww.astercity.net%2F~azakrze3%2Fhtml%2Fwin32_api_functios.html


Use the primary source for such info:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms724295%28v=vs.85%29.aspx

One possibly important point there is the WINAPI part, which describes 
how parameters are passed to and from the function, which might be the 
only cause that this doesn't work. However, instead of try-and-error, 
rather go to the documentation of the ctypes API and search for WINAPI. 
There, you will find an example that uses a function from the win32 API, 
too. A bit further down, you will also find a create_string_buffer() 
function that could be useful for you.


http://docs.python.org/2/library/ctypes.html


Greetings!

Uli

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


Re: Error .. Please Help

2012-12-13 Thread inshu chauhan
>
> if-else doesn't define a loop, but each of the for statements do.
>
> You have defined a classification for 8 of the possible colors, leaving
> millions of them undefined.  If the first time through the loop you
> manage to hit one of those undefined ones, you'll have no value for
> classification.  So you get an exception.
>

Yes, You are right that I will hit an exception if classification doesnot
have any value.
But as for the colors, actually I myself have colored the image using these
8 colors
but still I think in some pixels I have put more than 1 color, thats why
different colors are being encountered.

>
> Worse, if you manage to get past that first pixel with a valid
> classification, then for remaining pixels, you'll be using the last
> 'valid' classification encountered.  This is the kind of "quiet failure"
> that programmers dread.  Something that seems to work, but isn't even
> close.
>

For this I put an else clause at end but is there a better way to avoid
this kind of situation ??

>
> If you're going to print (to file) on each iteration through the loop
> (except 0,0,0), you need to make sure there's always a valid value.  So
> you need at least one more classification value, and an else clause to
> assign it, as ChrisA pointed out.
>
> Do you have a reason for treating (0,0,0) specially?  When that value is
> seen, the logic skips the print as well, since continue skips to the
> next loop iteration.
>

Yes , I have to skip (0,0,0), that is a kind of requirement.

>
> Are you really getting floating point values, or are they always going
> to be equal to an integer?  Those if/elif statements might be a problem
> if you ever need to compare to a value like (128.4, 255.0, 255.0).
>

I dont have values with decimal part, All values are integer.

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


Re: Error .. Please Help

2012-12-13 Thread Chris Angelico
On Thu, Dec 13, 2012 at 8:23 PM, inshu chauhan  wrote:
>> Are you really getting floating point values, or are they always going
>> to be equal to an integer?  Those if/elif statements might be a problem
>> if you ever need to compare to a value like (128.4, 255.0, 255.0).
>
>
> I dont have values with decimal part, All values are integer.

Find out how the tuples are actually being given to you. Floating
point values are rather annoying when it comes to comparisons. Try
printing out one of the tuples; I would hope that it has integer
values, not floats, in it.

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


Where to contribute Unicode General Category encoding/decoding

2012-12-13 Thread Pander Musubi
Hi all,

I have created some handy code to encode and decode Unicode General Categories. 
To which Python Package should I contribute this?

Regards,

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


Re: Problem with calling function from dll

2012-12-13 Thread Duncan Booth
deep...@poczta.fm wrote:

> I have problem with using function from dll.
> 
> import ctypes
> 
> b = ctypes.windll.LoadLibrary("kernel32")
> 
> a = ""
> 
> b.GetComputerNameA(a,20)
> 
> 
> But I got exception:
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> b.GetComputerNameA(a,20)
> WindowsError: exception: access violation reading 0x0014
> 
> Even when I write:
> a = ctypes.c_char_p('.' * 20)
> I got the same result.
> 
> Here I found this function description:
> http://sd2cx1.webring.org/l/rd?ring=pbring;id=15;url=http%3A%2F%
2Fwww.a
> stercity.net%2F~azakrze3%2Fhtml%2Fwin32_api_functios.html 
> 
> 
> Please help.

You have to allocate a buffer for the result, and the second parameter 
is a pointer to the length of the buffer on input and contains the 
length of the result on output.

#!python2.7

from ctypes import windll, c_wchar_p, POINTER, c_int, 
create_unicode_buffer
kernel32 = windll.LoadLibrary("kernel32")
_GetComputerNameW = kernel32.GetComputerNameW
_GetComputerNameW.argtypes = [c_wchar_p, POINTER(c_int)]
_GetComputerNameW.restype = c_int

def GetComputerName():
buf = create_unicode_buffer(255)
len = c_int(255)
if not _GetComputerNameW(buf, len):
raise RuntimeError("Failed to get computer name")
return buf.value[:len.value]

print GetComputerName()


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing tread collisions

2012-12-13 Thread Alexander Blinne
Am 12.12.2012 21:29, schrieb Dave Angel:
> On 12/12/2012 03:11 PM, Wanderer wrote:
>> I have a program that has a main GUI and a camera. In the main GUI, you can 
>> manipulate the images taken by the camera. You can also use the menu to 
>> check the camera's settings. Images are taken by the camera in a separate 
>> thread, so the long exposures don't block the GUI. I block conflicts between 
>> the camera snapshot thread and the main thread by setting a flag called 
>> self.cameraActive. I check to see if the cameraActive flag is false and set 
>> the cameraActive to True just before starting the thread. I generate an 
>> event on exiting the thread which sets the cameraActive flag to False. I 
>> also check and set and reset the flag in all the menu commands that access 
>> the camera. Like this.
>>
>> def onProperties(self, event):
>> """ Display a message window with the camera properties
>> event -- The camera properties menu event
>> """
>> # Update the temperature
>> if not self.cameraActive:
>> self.cameraActive = True
>> self.camera.getTemperature()
>> camDict = self.camera.getPropertyDict()
>> self.cameraActive = False
>> else:
>> camDict = {'Error': 'Camera Busy'}
>> dictMessage(camDict, 'Camera Properties')
>>
>> This works 
> 
> I don't think so.  in between the if and the assignment, another thread
> could get in there and also set the flag.  Then when either one of them
> finishes, it'll clear the flag and the other code is unprotected.

I have a general question about this kinds of things. I see that the
above is a common use case for some kind of lock which does this
testing/locking atomically. But the question is: if I know for sure that
there is no other thread that might get in the way this solution would
be fine, right?

In one of my applications i have a somewhat different case: i have a
list of objects and call the same method of each object, each in its own
thread (which is created and later joined just for this purpose). The
objects are thus only used by that one thread, the main thread waits for
all threads to be finished before accessing those objects again. Do i
really need some kind of locking for those objects?

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


Re: Problem with calling function from dll

2012-12-13 Thread deepblu
sb = ctypes.create_string_buffer(20)
i = ctypes.byref(ctypes.c_int(20))
w = b.GetComputerNameA(sb,i)

w -> 1
sb.value -> nazwa komputera

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


Find lowest level directory

2012-12-13 Thread loial
How can I find the full path of the lowest level directory in a directory 
structure?
 
If there is more than one directory at the lowest level, the first one found 
will be enough.

Any help appreciated
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find lowest level directory

2012-12-13 Thread Mark Lawrence

On 13/12/2012 12:48, loial wrote:

How can I find the full path of the lowest level directory in a directory 
structure?

If there is more than one directory at the lowest level, the first one found 
will be enough.

Any help appreciated



Take a look at the os.path functions.  Note that os.path.walk in Python 
2 is called os.walk in Python 3.


--
Cheers.

Mark Lawrence.

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


Re: Where to contribute Unicode General Category encoding/decoding

2012-12-13 Thread Bruno Dupuis
On Thu, Dec 13, 2012 at 01:51:00AM -0800, Pander Musubi wrote:
> Hi all,
> 
> I have created some handy code to encode and decode Unicode General 
> Categories. To which Python Package should I contribute this?
> 

Hi,

As said in a recent thread (a graph data structure IIRC), talking about
new features is far better if we see the code, so anyone can figure what
the code really does.

Can you provide a public repository uri or something?

Standard lib inclusions are not trivial, it most likely happens for well-known,
mature, PyPI packages, or battle-tested code patterns. Therefore, it's
often better to make a package on PyPI, or, if the code is too short, to submit
your handy chunks on ActiveState. If it deserves a general approbation, it
may be included in Python stdlib.

Cheers

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


Re: Error .. Please Help

2012-12-13 Thread Neil Cerutti
On 2012-12-13, inshu chauhan  wrote:
> For this I put an else clause at end but is there a better way
> to avoid this kind of situation ??

An if-elif-else structure is usually broken if you leave out the
else part. When I don't expect it to ever actually happen when
the program is working correctly it looks like this:

   else:
  raise SomeException("{} can't happen!".format(the_context))

else: raise exception constructs have saved me a lot of time.

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


Help with unittest2

2012-12-13 Thread Daniel Laird
All,

I am new to python and am stuck with python 2.6 (Ubuntu 10.04 and dont want to 
force switch to 2.7)
I want to use assertListEqual and other new test functions.
However
I do am import unittest2 as unittest
The code does not fail but any use of the new functions results in:
NameError: global name 'assertListEqual' is not defined

What am I doing wrong?
Do I need to change something else? The docs seem to imply what I have done is 
enough.

Hope you can help
Cheers
Dan L
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with unittest2

2012-12-13 Thread Miki Tebeka
On Thursday, December 13, 2012 7:03:27 AM UTC-8, Daniel Laird wrote: 
> I do am import unittest2 as unittest
> NameError: global name 'assertListEqual' is not defined
According to the docs 
(http://docs.python.org/2/library/unittest.html#unittest.TestCase.addTypeEqualityFunc)
 assertListEqual and friends was added in 2.7.

You can use assertEuqal, or if you don't care about order 
assertEqual(sorted(a), sorted(b)).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error .. Please Help

2012-12-13 Thread Dave Angel
On 12/13/2012 04:23 AM, inshu chauhan wrote:
>>
>> if-else doesn't define a loop, but each of the for statements do.
>>
>> You have defined a classification for 8 of the possible colors, leaving
>> millions of them undefined.  If the first time through the loop you
>> manage to hit one of those undefined ones, you'll have no value for
>> classification.  So you get an exception.
>>
> 
> Yes, You are right that I will hit an exception if classification doesnot
> have any value.
> But as for the colors, actually I myself have colored the image using these
> 8 colors
> but still I think in some pixels I have put more than 1 color, thats why
> different colors are being encountered.
> 
>>
>> Worse, if you manage to get past that first pixel with a valid
>> classification, then for remaining pixels, you'll be using the last
>> 'valid' classification encountered.  This is the kind of "quiet failure"
>> that programmers dread.  Something that seems to work, but isn't even
>> close.
>>
> 
> For this I put an else clause at end but is there a better way to avoid
> this kind of situation ??

Why would you want to avoid it?  It has showed you there's a bug
somewhere.  That's better than silently doing something wrong.  As
ChrisA has said, you probably should raise your own exception in the
else clause, explaining to the user that the data file is invalid, and
exactly why.


> 
>>
>> If you're going to print (to file) on each iteration through the loop
>> (except 0,0,0), you need to make sure there's always a valid value.  So
>> you need at least one more classification value, and an else clause to
>> assign it, as ChrisA pointed out.
>>
>> Do you have a reason for treating (0,0,0) specially?  When that value is
>> seen, the logic skips the print as well, since continue skips to the
>> next loop iteration.
>>
> 
> Yes , I have to skip (0,0,0), that is a kind of requirement.
>

That's fine.

>>
>> Are you really getting floating point values, or are they always going
>> to be equal to an integer?  Those if/elif statements might be a problem
>> if you ever need to compare to a value like (128.4, 255.0, 255.0).
>>
> 
> I dont have values with decimal part, All values are integer.
> 

Then why are you comparing to floats?  It'd be faster and clearer and
less typing if you just use ints.  That is of course assuming that the
values returned by image[y,x] are a tuple of ints.  You can check that
by doing something like
print [type(i) for i in color]

Is there any chance the image is 16 bits per pixel?

-- 

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


Re: Where to contribute Unicode General Category encoding/decoding

2012-12-13 Thread Pander Musubi
On Thursday, December 13, 2012 2:22:57 PM UTC+1, Bruno Dupuis wrote:
> On Thu, Dec 13, 2012 at 01:51:00AM -0800, Pander Musubi wrote:
> 
> > Hi all,
> 
> > 
> 
> > I have created some handy code to encode and decode Unicode General 
> > Categories. To which Python Package should I contribute this?
> 
> > 
> 
> 
> 
> Hi,
> 
> 
> 
> As said in a recent thread (a graph data structure IIRC), talking about
> 
> new features is far better if we see the code, so anyone can figure what
> 
> the code really does.
> 
> 
> 
> Can you provide a public repository uri or something?
> 
> 
> 
> Standard lib inclusions are not trivial, it most likely happens for 
> well-known,
> 
> mature, PyPI packages, or battle-tested code patterns. Therefore, it's
> 
> often better to make a package on PyPI, or, if the code is too short, to 
> submit
> 
> your handy chunks on ActiveState. If it deserves a general approbation, it
> 
> may be included in Python stdlib.

I was expecting PyPI. Here is the code, please advise on where to submit it:
  http://pastebin.com/dbzeasyq

> Cheers
> 
> 
> 
> -- 
> 
> Bruno

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


Re: Help with unittest2

2012-12-13 Thread Daniel Laird
On Thursday, December 13, 2012 3:09:58 PM UTC, Miki Tebeka wrote:
> On Thursday, December 13, 2012 7:03:27 AM UTC-8, Daniel Laird wrote: 
> 
> > I do am import unittest2 as unittest
> 
> > NameError: global name 'assertListEqual' is not defined
> 
> According to the docs 
> (http://docs.python.org/2/library/unittest.html#unittest.TestCase.addTypeEqualityFunc)
>  assertListEqual and friends was added in 2.7.
> 
> 
> 
> You can use assertEuqal, or if you don't care about order 
> assertEqual(sorted(a), sorted(b)).

Thanks, however I thought by using unittest2 it added the new 2.7 features to 
2.6?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find lowest level directory

2012-12-13 Thread Peter Otten
loial wrote:

> How can I find the full path of the lowest level directory in a directory
> structure?
>  
> If there is more than one directory at the lowest level, the first one
> found will be enough.

import os

def directories(root):
for path, folders, files in os.walk(root):
for name in folders:
yield os.path.join(path, name)

def depth(path):
return path.count(os.sep)

some_folder = ...
print max(directories(some_folder), key=depth)


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


Re: Help with unittest2

2012-12-13 Thread Boris FELD
How are you importing unittest2, do you have something like this ?

try:
  import unittest2 as unittest
except ImportError:
  import unittest

If it's the case, you are maybe using default unittest while you think
you are using unittest2.

2012/12/13 Daniel Laird :
> On Thursday, December 13, 2012 3:09:58 PM UTC, Miki Tebeka wrote:
>> On Thursday, December 13, 2012 7:03:27 AM UTC-8, Daniel Laird wrote:
>>
>> > I do am import unittest2 as unittest
>>
>> > NameError: global name 'assertListEqual' is not defined
>>
>> According to the docs 
>> (http://docs.python.org/2/library/unittest.html#unittest.TestCase.addTypeEqualityFunc)
>>  assertListEqual and friends was added in 2.7.
>>
>>
>>
>> You can use assertEuqal, or if you don't care about order 
>> assertEqual(sorted(a), sorted(b)).
>
> Thanks, however I thought by using unittest2 it added the new 2.7 features to 
> 2.6?
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with unittest2

2012-12-13 Thread Dave Angel
On 12/13/2012 10:03 AM, Daniel Laird wrote:
> All,
>
> I am new to python and am stuck with python 2.6 (Ubuntu 10.04 and dont want 
> to force switch to 2.7)
> I want to use assertListEqual and other new test functions.
> However
> I do am import unittest2 as unittest
> The code does not fail but any use of the new functions results in:
> NameError: global name 'assertListEqual' is not defined
>
> What am I doing wrong?
> Do I need to change something else? The docs seem to imply what I have done 
> is enough.

Where's your code?  And the full traceback from the error?  From what
you say, I can't imagine how it would work, so my mind assumes something
different.  You should be able to demonstrate the problem with a two
line sample program.  Pasted from a real test, not paraphrased.

You do know that you'll need
unittest.assertListEqual()

right?  That's because you used
import unittest2 as unittest

rather than
from unittest2 import assertListEqual
 

You can tell what names are in the unittest namespace by doing a
dir(unittest).  Although that's normally done interactively, it'll work
fine from your code, as long as you put it before the spot where the
exception happens.



-- 

DaveA

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


Re: Help with unittest2

2012-12-13 Thread Thomas Bach
Hi,

On Thu, Dec 13, 2012 at 07:03:27AM -0800, Daniel Laird wrote:
> I do am import unittest2 as unittest
> The code does not fail but any use of the new functions results in:
> NameError: global name 'assertListEqual' is not defined
> 
> What am I doing wrong?

Read the error message again: it says that it cannot find the _global_
name 'assertListEqual'!

assertListEqual is a method of unittest.TestCase. Hence, it has to be
called on a unittest.TestCase instance, such as

import unittest

class FooTests(unittest.TestCase):

def test_a_list(self):
a = ['foo', 'bar']
b = ['foo', 'bar']
self.assertListEqual(a, b)

BTW, I actually never used 'assertTypeEqual'. I rather call
assertEqual and let unittest do the internals. I think assertEqual
calls the right method for you depending on the arguments type. If you
want to make sure that something is of a certain type use
assertIsInstance!

Hope this helps,

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


Re: Help with unittest2

2012-12-13 Thread Paul Rudin
Thomas Bach  writes:


> BTW, I actually never used 'assertTypeEqual' I rather call assertEqual
> and let unittest do the internals. I think assertEqual calls the right
> method for you depending on the arguments type. 


The assertEqual methods have the advantage of checking the type of
the arguments. assertEqual would be OK with equal numerical arguments,
but that would be an inferior test if you were really expecting two
lists.

> If you want to make sure that something is of a certain type use
> assertIsInstance!

Yes, but why do something in 3 lines when there's a perfectly good
method provided that allows you do to it directly in one?

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


Re: Preventing tread collisions

2012-12-13 Thread Ian Kelly
On Thu, Dec 13, 2012 at 3:26 AM, Alexander Blinne  wrote:
> I have a general question about this kinds of things. I see that the
> above is a common use case for some kind of lock which does this
> testing/locking atomically. But the question is: if I know for sure that
> there is no other thread that might get in the way this solution would
> be fine, right?

If you know for sure that there is no other thread, then there is no
need for the flag in the first place.

> In one of my applications i have a somewhat different case: i have a
> list of objects and call the same method of each object, each in its own
> thread (which is created and later joined just for this purpose). The
> objects are thus only used by that one thread, the main thread waits for
> all threads to be finished before accessing those objects again. Do i
> really need some kind of locking for those objects?

No, if a resource is only ever used by one thread/process, then there
is no reason to lock it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing tread collisions

2012-12-13 Thread Wanderer
On Wednesday, December 12, 2012 3:53:28 PM UTC-5, MRAB wrote:
> On 2012-12-12 20:11, Wanderer wrote:
> 
> > I have a program that has a main GUI and a camera. In the main GUI, you can 
> > manipulate the images taken by the camera. You can also use the menu to 
> > check the camera's settings. Images are taken by the camera in a separate 
> > thread, so the long exposures don't block the GUI. I block conflicts 
> > between the camera snapshot thread and the main thread by setting a flag 
> > called self.cameraActive. I check to see if the cameraActive flag is false 
> > and set the cameraActive to True just before starting the thread. I 
> > generate an event on exiting the thread which sets the cameraActive flag to 
> > False. I also check and set and reset the flag in all the menu commands 
> > that access the camera. Like this.
> 
> >
> 
> >  def onProperties(self, event):
> 
> >  """ Display a message window with the camera properties
> 
> >  event -- The camera properties menu event
> 
> >  """
> 
> >  # Update the temperature
> 
> >  if not self.cameraActive:
> 
> >  self.cameraActive = True
> 
> >  self.camera.getTemperature()
> 
> >  camDict = self.camera.getPropertyDict()
> 
> >  self.cameraActive = False
> 
> >  else:
> 
> >  camDict = {'Error': 'Camera Busy'}
> 
> >  dictMessage(camDict, 'Camera Properties')
> 
> >
> 
> > This works but my question is, is there a better way using semaphores, 
> > locks or something else to prevent collisions between threads?
> 
> >
> 
> That suffers from a race condition in that self.cameraActive might be
> 
> False when it's checked in the 'if' condition but set to True just
> 
> afterwards by the other thread.
> 
> 
> 
> You could try a non-blocking semaphore:
> 
> 
> 
> def __init__(self):
> 
>  self.cameraActive = Semaphore()
> 
> 
> 
> def onProperties(self, event):
> 
>  """ Display a message window with the camera properties
> 
>  event -- The camera properties menu event
> 
>  """
> 
>  # Update the temperature
> 
>  if self.cameraActive.acquire(False): # Non-blocking
> 
>  # Successfully acquired the semaphore, so the camera wasn't active
> 
>  self.camera.getTemperature()
> 
>  camDict = self.camera.getPropertyDict()
> 
>  self.cameraActive.release()
> 
>  else:
> 
>  camDict = {'Error': 'Camera Busy'}

Thanks. Why Non-blocking?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing tread collisions

2012-12-13 Thread Dave Angel
On 12/13/2012 11:36 AM, Wanderer wrote:
> 
>
> Thanks. Why Non-blocking?

You said you didn't want the GUI to lock up.  Non-blocking lets you
choose alternative action when you would otherwise have to wait for the
resource.



-- 

DaveA

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


Re: Preventing tread collisions

2012-12-13 Thread Wanderer
On Thursday, December 13, 2012 11:54:10 AM UTC-5, Dave Angel wrote:
> On 12/13/2012 11:36 AM, Wanderer wrote:
> 
> > 
> 
> >
> 
> > Thanks. Why Non-blocking?
> 
> 
> 
> You said you didn't want the GUI to lock up.  Non-blocking lets you
> 
> choose alternative action when you would otherwise have to wait for the
> 
> resource.
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

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


What package to use for certificate manipulation (signing, hashing)

2012-12-13 Thread Nenad Cikic
Hello,
I have my pfx file.
I need to sign xml with this pfx using private key.
I need to extract pem,issuer name,sb,subjectname which all I did with pyopenssl.
I need to compute also md5 and  sha-1.
If I got it right pyopenssl can not sign or compute hash.
Shall i use m2crypto or python-crypto or both?
With pyopenssl it was eassy to extract pem and certificate information from pfx.
Can it be done with m2crypto? I am looking at the docs but can not find how.

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


log4py confusion

2012-12-13 Thread Rob Richardson
Greetings!



I have finally gotten fed up with all of the Python scripts used in my company 
that have every parameter hard-coded.  I am rewriting one of them to read all 
of its parameters from an XML file.  Then, we can change the XML file to 
control which database it is using, whether its running in debug mode or not, 
and various other things.  One of the parameters I want the XML file to contain 
is the name of the script's log file.



I have a class named Settings that will contain all the parameters read from 
the XML file.  But if something goes wrong, I want to log it.  So, I want to 
have a Logger object for it to use.  I use a hard-coded file name for that.  
Then, after reading the XML file, I want to create a second Logger object that 
will be used by the rest of the script.



When I try to use the second Logger object, I get an exception complaining that 
'unicode' object has no attribute 'write'.



The script and the exception messages are below.  Can anyone see what I'm doing 
wrong?



Can anyone point me to a web site documenting the log4py module?



Thank you very much.



RobR





import os

import sys

import string

import win32api

import win32event

import win32com

import win32com.client

import win32net

import pythoncom

import time

import log4py

import xml.dom.minidom as minidom

import argparse



#Set to 1 to run loop once for debugging, set to 0 for operation

#Debug = 1



class DataElement:

value = None



def __init__(self, element = None):

if element != None:

self.GetData(element)



def GetData(self, element):

nodes = element.childNodes

for node in nodes:

if node.nodeType == node.TEXT_NODE:

self.value = node.data



def GetDataFromRoot(self, rootElement, targetName, defaultValue):

elements = rootElement.getElementsByTagName(targetName)

if elements:

dataElement = DataElement(elements[0])

if (dataElement):

self.value = dataElement.value

else:

self.value = defaultValue

else:

self.Value = defaultValue



def __nonzero__(self):

return self.value != None



class Settings:

logFile = "TaskToCrane_somethingnew.log"



def __init__(self):

print "I don't know what XML file to use yet."



def __init__(self, fileName, tempLogger):

tempLogger.info( "Settings will come from " + fileName)

settingsDoc = minidom.parse(fileName)

rootElement = settingsDoc.documentElement

# print "Root element name: " + rootElement.tagName



programControlElement = 
rootElement.getElementsByTagName("ProgramControl")[0]

logFileElement = DataElement()

logFileElement.GetDataFromRoot(programControlElement, "LogFile", 
self.logFile)

if logFileElement:

self.logFile = logFileElement.value

else:

tempLogger.error("Failed to get log file name.")



def Log(self, logger):

logger.info("Log file: " + str(self.logFile))



if __name__ == "__main__" :



TempLogger = log4py.Logger().get_instance("main")

TempLogger.set_rotation(log4py.ROTATE_DAILY, 5)



TempLogger.set_loglevel(log4py.LOGLEVEL_DEBUG)

TempLogger.set_formatstring("%T - %L  %M")

TempLogger.set_target("TaskToCrane_logging_base.log")



parser = argparse.ArgumentParser()

parser.add_argument("settings_file")

args = parser.parse_args()



programSettings = Settings(args.settings_file, TempLogger)

TempLogger.info("Setting actual log target to " + programSettings.logFile)



Logger = log4py.Logger().get_instance("main")

Logger.set_rotation(log4py.ROTATE_DAILY, 5)



Logger.set_loglevel(log4py.LOGLEVEL_DEBUG)

Logger.set_formatstring("%T - %L  %M")

Logger.set_target(programSettings.logFile)



programSettings.Log(TempLogger)



Traceback (most recent call last):

  File 
"D:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 
322, in RunScript

debugger.run(codeObject, __main__.__dict__, start_stepping=0)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", 
line 60, in run

_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", 
line 655, in run

exec cmd in globals, locals

  File "D:\Program Files\WinCaps\Scripts\TaskToCrane_logging.py", line 91, in 


programSettings.Log(TempLogger)

  File "D:\Program Files\WinCaps\Scripts\TaskToCrane_logging.py", line 66, in 
Log

logger.info("Log file: " + str(self.logFile))

  File "log4py.py", line 359, in info

self.__Logger_showmessage(message, MSG_INFO)

 File "log4py.py", line 534, in __Logger_showmessage

target.write("%s\n" % line)

AttributeError: 'unicode' object h
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python parser problem

2012-12-13 Thread RCU

  Dave,
Thanks for the reply.
The script was originally edited on Windows with proper \r\n endings, but the 
PythonTidy script somehow does the doubling (I guess it assumes UNIX format only), i.e., 
\r\r\n . So indeed, that's kind of messy (and the Python Lang Reference specifies clearly 
it interprets \r as a newline, as well) and I didn't realize it with my editor. After 
running dos2unix (twice) on the script I cleaned all \r and it went OK.


I guess Python is complaining at line 30 and not at the previous lines, because of 
the line-breaking backslash.


  Best regards,
Alex

On 12/12/2012 9:59 PM, Dave Angel wrote:

On 12/12/2012 02:10 PM, RCU wrote:

   Hello.
 I would like to report a parser bug manifesting on Python 2.5, 2.7
(but not on 2.2) and 3.3.
 Please see the attached script.
 Basically this bug appeared after applying PythonTidy on a valid
script.

 More exactly, when running:
 python -c "import iCam_GIT5_5"
   I get:
 Traceback (most recent call last):
   File "", line 1, in
   File "iCam_GIT5_5.py", line 60

 ^
 SyntaxError: invalid syntax

 Actually, the error reported by Python is a bug, as far as I see:
the line 60 reported in the script does not actually contain the text
reported in the error, and this makes quite difficult locating the
so-called error.


No, the error is on line 60.  You have blank line between each line, but
your editor apparently doesn't show you that.

Your line-endings are messed up.  Here's a dump of the first two lines.
(using hexdump -C)

  43 55 52 52 45 4e 54 5f  52 45 4c 45 41 53 45 5f
|CURRENT_RELEASE_|
0010  54 49 4d 45 20 3d 20 27  32 30 31 32 5f 31 32 5f  |TIME =
'2012_12_|
0020  31 30 5f 31 33 5f 30 30  5f 30 30 27 0d 0d 0a 4e
|10_13_00_00'...N|

Notice that the line ends with 0d0d0a, or \r\r\n.  That's not valid.
Apparently python's logic considers that as a line ending with \r,
followed by a blank line ending with\r\n.



 In fact the error is at script line 30: we should have all the
code on one line, like this
 playlistToUse = youtubeClient.AddPlaylist(playlistTitle,
playlistTitle, playlist_private=False).
 The "\" used in the script to break the line in 2 is a
reminiscence of running PythonTidy-1.22.python (so fixing this bug
would be directly relevant when using PythonTidy).


Nothing wrong with ending with a backslash for continuation.  Backslash
continues the line onto the next one, which is blank.  Remove the extra
\r there and it'll be fine.



 With this occasion I would like to ask also what are the limits of
the Python 2.x and 3.x parser. Where can I find what are the limits on
the size/lines of the parsed script?


Can't help there.





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


RE: log4py confusion

2012-12-13 Thread Rob Richardson
The last line,

programSettings.Log(TempLogger),
should have been

programSettings.Log(Logger)

I get the same error no matter which logger I use, though, which I don't 
understand.

Also, I'm using Python 2.7.

Thanks again for your help!

RobR
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
Rob Richardson
Sent: Thursday, December 13, 2012 1:58 PM
To: python-list@python.org
Subject: log4py confusion


Greetings!



I have finally gotten fed up with all of the Python scripts used in my company 
that have every parameter hard-coded.  I am rewriting one of them to read all 
of its parameters from an XML file.  Then, we can change the XML file to 
control which database it is using, whether its running in debug mode or not, 
and various other things.  One of the parameters I want the XML file to contain 
is the name of the script's log file.



I have a class named Settings that will contain all the parameters read from 
the XML file.  But if something goes wrong, I want to log it.  So, I want to 
have a Logger object for it to use.  I use a hard-coded file name for that.  
Then, after reading the XML file, I want to create a second Logger object that 
will be used by the rest of the script.



When I try to use the second Logger object, I get an exception complaining that 
'unicode' object has no attribute 'write'.



The script and the exception messages are below.  Can anyone see what I'm doing 
wrong?



Can anyone point me to a web site documenting the log4py module?



Thank you very much.



RobR





import os

import sys

import string

import win32api

import win32event

import win32com

import win32com.client

import win32net

import pythoncom

import time

import log4py

import xml.dom.minidom as minidom

import argparse



#Set to 1 to run loop once for debugging, set to 0 for operation

#Debug = 1



class DataElement:

value = None



def __init__(self, element = None):

if element != None:

self.GetData(element)



def GetData(self, element):

nodes = element.childNodes

for node in nodes:

if node.nodeType == node.TEXT_NODE:

self.value = node.data



def GetDataFromRoot(self, rootElement, targetName, defaultValue):

elements = rootElement.getElementsByTagName(targetName)

if elements:

dataElement = DataElement(elements[0])

if (dataElement):

self.value = dataElement.value

else:

self.value = defaultValue

else:

self.Value = defaultValue



def __nonzero__(self):

return self.value != None



class Settings:

logFile = "TaskToCrane_somethingnew.log"



def __init__(self):

print "I don't know what XML file to use yet."



def __init__(self, fileName, tempLogger):

tempLogger.info( "Settings will come from " + fileName)

settingsDoc = minidom.parse(fileName)

rootElement = settingsDoc.documentElement

# print "Root element name: " + rootElement.tagName



programControlElement = 
rootElement.getElementsByTagName("ProgramControl")[0]

logFileElement = DataElement()

logFileElement.GetDataFromRoot(programControlElement, "LogFile", 
self.logFile)

if logFileElement:

self.logFile = logFileElement.value

else:

tempLogger.error("Failed to get log file name.")



def Log(self, logger):

logger.info("Log file: " + str(self.logFile))



if __name__ == "__main__" :



TempLogger = log4py.Logger().get_instance("main")

TempLogger.set_rotation(log4py.ROTATE_DAILY, 5)



TempLogger.set_loglevel(log4py.LOGLEVEL_DEBUG)

TempLogger.set_formatstring("%T - %L  %M")

TempLogger.set_target("TaskToCrane_logging_base.log")



parser = argparse.ArgumentParser()

parser.add_argument("settings_file")

args = parser.parse_args()



programSettings = Settings(args.settings_file, TempLogger)

TempLogger.info("Setting actual log target to " + programSettings.logFile)



Logger = log4py.Logger().get_instance("main")

Logger.set_rotation(log4py.ROTATE_DAILY, 5)



Logger.set_loglevel(log4py.LOGLEVEL_DEBUG)

Logger.set_formatstring("%T - %L  %M")

Logger.set_target(programSettings.logFile)



programSettings.Log(TempLogger)



Traceback (most recent call last):

  File 
"D:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 
322, in RunScript

debugger.run(codeObject, __main__.__dict__, start_stepping=0)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", 
line 60, in run

_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", 
line 655, in run

exec cmd in globals, locals

  File "D:\Program Files\WinCaps\Scripts\TaskToCrane_logging.py", lin

Re: log4py confusion

2012-12-13 Thread MRAB

On 2012-12-13 18:58, Rob Richardson wrote:

Greetings!

I have finally gotten fed up with all of the Python scripts used in my
company that have every parameter hard-coded.  I am rewriting one of
them to read all of its parameters from an XML file.  Then, we can
change the XML file to control which database it is using, whether its
running in debug mode or not, and various other things.  One of the
parameters I want the XML file to contain is the name of the script's
log file.

I have a class named Settings that will contain all the parameters read
from the XML file.  But if something goes wrong, I want to log it.  So,
I want to have a Logger object for it to use.  I use a hard-coded file
name for that.  Then, after reading the XML file, I want to create a
second Logger object that will be used by the rest of the script.

When I try to use the second Logger object, I get an exception
complaining that 'unicode' object has no attribute 'write'.

The script and the exception messages are below.  Can anyone see what
I'm doing wrong?


[snip]
I think the problem might be that it's expecting a file object, not a
file name/path as you have here:

TempLogger.set_target("TaskToCrane_logging_base.log")

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


unpacking first few items of iterable

2012-12-13 Thread Daniel Fetchinson
Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking first few items of iterable

2012-12-13 Thread Demian Brecht
If you're using python3, you can simply do:

a, b, c, *rest = myiterable

Demian Brecht
http://demianbrecht.github.com




On 2012-12-13 11:37 AM, "Daniel Fetchinson" 
wrote:

>Hi folks, I swear I used to know this but can't find it anywhere:
>
>What's the standard idiom for unpacking the first few items of an
>iterable whose total length is unknown?
>
>Something like
>
>a, b, c, _ = myiterable
>
>where _ could eat up a variable number of items, in case I'm only
>interested in the first 3 items?
>
>Cheers,
>Daniel
>
>
>-- 
>Psss, psss, put it down! - http://www.cafepress.com/putitdown
>-- 
>http://mail.python.org/mailman/listinfo/python-list


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


RE: log4py confusion

2012-12-13 Thread Rob Richardson
Thanks for the suggestion, but I don't think that can be it.  At least, it's 
not it on the line you specified.  That form, with the target name given as a 
hard-coded string, is in use in every Python script our company uses.  So, 
set_target() is expecting a file instead of a file name, there must be some 
implicit conversion going on that creates a file object of the given name 
before setting the log target to the file.  

On the other hand, it would certainly explain the " 'Unicode' object does not 
have attribute 'write' " message.  A file object would be expected to have an 
attribute named 'write', while a string object wouldn't.  

The error happens after the target is changed to a file name contained in a 
variable.  Why doesn't that implicit conversion work with a string contained in 
a variable?  Do I have to do an explicit cast of some kind?  Or, probably 
better, I should probably look up how to create a file object so I can pass it 
in to the set_target() function.

That's one reason I asked for documentation on log4py: so I could see what 
methods are available, and what arguments they actually expect.

Thanks again!

RobR


-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
MRAB
Sent: Thursday, December 13, 2012 2:35 PM
To: python-list@python.org
Subject: Re: log4py confusion

On 2012-12-13 18:58, Rob Richardson wrote:
> Greetings!
>
> I have finally gotten fed up with all of the Python scripts used in my 
> company that have every parameter hard-coded.  I am rewriting one of 
> them to read all of its parameters from an XML file.  Then, we can 
> change the XML file to control which database it is using, whether its 
> running in debug mode or not, and various other things.  One of the 
> parameters I want the XML file to contain is the name of the script's 
> log file.
>
> I have a class named Settings that will contain all the parameters 
> read from the XML file.  But if something goes wrong, I want to log 
> it.  So, I want to have a Logger object for it to use.  I use a 
> hard-coded file name for that.  Then, after reading the XML file, I 
> want to create a second Logger object that will be used by the rest of the 
> script.
>
> When I try to use the second Logger object, I get an exception 
> complaining that 'unicode' object has no attribute 'write'.
>
> The script and the exception messages are below.  Can anyone see what 
> I'm doing wrong?
>
[snip]
I think the problem might be that it's expecting a file object, not a file 
name/path as you have here:

 TempLogger.set_target("TaskToCrane_logging_base.log")

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


wxFormBuilder and wxBitmapCombobox

2012-12-13 Thread Lurken III


I'm stucked in populate a wxBitmapCombobox with wxFormBuilder

win7
wxFB 3.3.4-beta unicode



in Project settings, path = .<- (dot)
I have an "ico_conto1.bmp"

tree of the dialog:

- Dialog
--- wxBoxSizer
--wxGridSizer
-- 4 wxStaticText + 3 wxTextCtrl +
-- wxBitmapComboBox
--- wxStaticLine
--- wxStdDialogButtonSizer


in wxBitmapComboBox setup, in "choices"
I'm not able to load the bitmap

At the bottom, tip for such widget is  "use format bitmap:choice",

tested:

ico_conto1.bmp:bitmap1
bitmap:ico_conto1.bmp
bitmap:ico_conto1

but I get only and always a popup

"Can't load image from file 'ico_conto1.bmp": file does not exist."


Any help welcome, thanks.


--
Lurken III

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


RE: log4py confusion

2012-12-13 Thread Rob Richardson
I think I have the answer.  All I need to do is use the str() function to 
convert the object stored in logFile from a Unicode string to a normal string:

Logger.set_target(str(programSettings.logFile))

RobR

-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
Rob Richardson
Sent: Thursday, December 13, 2012 2:52 PM
To: python-list@python.org
Subject: RE: log4py confusion

Thanks for the suggestion, but I don't think that can be it.  At least, it's 
not it on the line you specified.  That form, with the target name given as a 
hard-coded string, is in use in every Python script our company uses.  So, 
set_target() is expecting a file instead of a file name, there must be some 
implicit conversion going on that creates a file object of the given name 
before setting the log target to the file.  

On the other hand, it would certainly explain the " 'Unicode' object does not 
have attribute 'write' " message.  A file object would be expected to have an 
attribute named 'write', while a string object wouldn't.  

The error happens after the target is changed to a file name contained in a 
variable.  Why doesn't that implicit conversion work with a string contained in 
a variable?  Do I have to do an explicit cast of some kind?  Or, probably 
better, I should probably look up how to create a file object so I can pass it 
in to the set_target() function.

That's one reason I asked for documentation on log4py: so I could see what 
methods are available, and what arguments they actually expect.

Thanks again!

RobR


-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
MRAB
Sent: Thursday, December 13, 2012 2:35 PM
To: python-list@python.org
Subject: Re: log4py confusion

On 2012-12-13 18:58, Rob Richardson wrote:
> Greetings!
>
> I have finally gotten fed up with all of the Python scripts used in my 
> company that have every parameter hard-coded.  I am rewriting one of 
> them to read all of its parameters from an XML file.  Then, we can 
> change the XML file to control which database it is using, whether its 
> running in debug mode or not, and various other things.  One of the 
> parameters I want the XML file to contain is the name of the script's 
> log file.
>
> I have a class named Settings that will contain all the parameters 
> read from the XML file.  But if something goes wrong, I want to log 
> it.  So, I want to have a Logger object for it to use.  I use a 
> hard-coded file name for that.  Then, after reading the XML file, I 
> want to create a second Logger object that will be used by the rest of the 
> script.
>
> When I try to use the second Logger object, I get an exception 
> complaining that 'unicode' object has no attribute 'write'.
>
> The script and the exception messages are below.  Can anyone see what 
> I'm doing wrong?
>
[snip]
I think the problem might be that it's expecting a file object, not a file 
name/path as you have here:

 TempLogger.set_target("TaskToCrane_logging_base.log")

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


python\bluetooth / wsgi / apache 2.2

2012-12-13 Thread Barry Dick
I'm wanting to read from my bluetooth device (it just sends data/header with a 
checksum at the end, in a continuous mode "a biofeedback device") and I'm 
getting a weird error in my logs not allowing me to use multiple sockets. I 
guess with wsgi, I'm creating a link/module between the two apis (apache / 
python), and then lets apache manage the socket / port communication on the 
application layer. How ever, I'm not able to connect to my device. Is there 
something simple I'm missing? The test code is the following

#!/usr/bin/python

# Written by Yevgeniy Medynskiy (euge...@gatech.edu)
# Date modified: December 2006
#
# No copyright. No warranty. Distributed as-is.
#
# http://www.gvu.gatech.edu/ccg/resources/wearableRFID.html

import time
import bluetooth
import sys

class MyWriter:

def __init__(self, stdout, filename):
#self.stdout = stdout
self.logfile = file(filename, 'a')

def write(self, text):
#self.stdout.write(text)
self.logfile.write(text)

def close(self):
#self.stdout.close()
self.logfile.close()

writer = MyWriter(sys.stdout, 'logging.txt')
sys.stdout = writer

#
## Change to your device's Bluetooth address
#
device = "10:00:E8:AC:4D:D0"

port = 1

#
## Read command and request for acknowledgement.
#

socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

#print "Attempting to connect to " + device + ":" + str(port) + "...",
socket.connect((device, port))
#print "done."

#print "Receiving data..."


data = ""
try:
while True:
try:
data = socket.recv(255)
except bluetooth.BluetoothError, b:
print "Bluetooth Error: ", b

if len(data) > 0: print data

except KeyboardInterrupt:
#print "Closing socket...",
socket.close()
#print "done."

[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] mod_wsgi (pid=2780): 
Target WSGI script 'C:/Project/index.py' cannot be loaded as Python module.
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] mod_wsgi (pid=2780): 
Exception occurred processing WSGI script 'C:/Project/index.py'.
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] Traceback (most recent 
call last):
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1]   File 
"C:/Project/index.py", line 45, in 
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] 
socket.connect((device, port))
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1]   File 
"C:\\Python26\\lib\\site-packages\\bluetooth\\msbt.py", line 53, in connect
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] bt.connect 
(self._sockfd, addr, port)
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] IOError: Only one usage 
of each socket address (protocol/network address/port) is normally permitted.\r
[Wed Dec 12 17:00:31 2012] [error] [client 127.0.0.1] 

I realize that in order for me to feed information back to apache and then onto 
my client, is I need to def application() but I wanted to make sure it was 
just that, and not something that I don't know about using sockets.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking first few items of iterable

2012-12-13 Thread MRAB

On 2012-12-13 19:37, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?


You could do this:

from itertools import islice

a, b, c = islice(myiterable, 3)

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


Re: unpacking first few items of iterable

2012-12-13 Thread Daniel Fetchinson
>>Hi folks, I swear I used to know this but can't find it anywhere:
>>
>>What's the standard idiom for unpacking the first few items of an
>>iterable whose total length is unknown?
>>
>>Something like
>>
>>a, b, c, _ = myiterable
>>
>>where _ could eat up a variable number of items, in case I'm only
>>interested in the first 3 items?
>
> If you're using python3, you can simply do:
>
> a, b, c, *rest = myiterable

Thanks, sounds great, how about python2?

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking first few items of iterable

2012-12-13 Thread Mitya Sirenef

On 12/13/2012 03:09 PM, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?

If you're using python3, you can simply do:

a, b, c, *rest = myiterable

Thanks, sounds great, how about python2?



If you know the sequence has at least n items, you
can do a, b, c = seq[:3]

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: unpacking first few items of iterable

2012-12-13 Thread Daniel Fetchinson
 Hi folks, I swear I used to know this but can't find it anywhere:

 What's the standard idiom for unpacking the first few items of an
 iterable whose total length is unknown?

 Something like

 a, b, c, _ = myiterable

 where _ could eat up a variable number of items, in case I'm only
 interested in the first 3 items?
>>> If you're using python3, you can simply do:
>>>
>>> a, b, c, *rest = myiterable
>> Thanks, sounds great, how about python2?
>>
>
> If you know the sequence has at least n items, you
> can do a, b, c = seq[:3]

Yeah, that's probably the simplest, without all the fancy stuff :)

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking first few items of iterable

2012-12-13 Thread Mitya Sirenef

On 12/13/2012 03:39 PM, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?

Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?

If you're using python3, you can simply do:

a, b, c, *rest = myiterable

Thanks, sounds great, how about python2?


If you know the sequence has at least n items, you
can do a, b, c = seq[:3]

Yeah, that's probably the simplest, without all the fancy stuff :)

Cheers,
Daniel





Well, fancy stuff is good too, I'm a great fan of fancy stuff :)

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: OOP noob question: Mixin properties

2012-12-13 Thread Micky Hulse
On Wed, Dec 12, 2012 at 7:49 PM, Micky Hulse  wrote:
> I hope you don't mind that this question involves Django... I'm just
> looking to improve my core Python skills (so, generic Python examples
> would be cool).

Just experimenting:



I think that will help me achieve my desired end result.

I'm open to feedback.

Cheers!
M
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking first few items of iterable

2012-12-13 Thread Ian Kelly
On Thu, Dec 13, 2012 at 1:39 PM, Daniel Fetchinson
 wrote:
>> If you know the sequence has at least n items, you
>> can do a, b, c = seq[:3]
>
> Yeah, that's probably the simplest, without all the fancy stuff :)

That only works for sequences, though.  Not all iterables are
sequences.  The islice version proposed by MRAB is more generally
applicable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with unittest2

2012-12-13 Thread Terry Reedy

On 12/13/2012 10:03 AM, Daniel Laird wrote:

All,

I am new to python and am stuck with python 2.6 (Ubuntu 10.04 and
dont want to force switch to 2.7)


You can altinstall 2.7 and leave the system 2.6 alone.


--
Terry Jan Reedy

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


Re: Python parser problem

2012-12-13 Thread Chris Angelico
On Fri, Dec 14, 2012 at 6:12 AM, RCU  wrote:
>   Dave,
> Thanks for the reply.
> The script was originally edited on Windows with proper \r\n endings,

It's worth noting that many Windows-based editors and interpreters are
quite happy with \n line endings. You may be able to save yourself
some trouble by switching everything to Unix newlines.

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


Re: Preventing tread collisions

2012-12-13 Thread Andrew Robinson

On 12/12/2012 12:29 PM, Dave Angel wrote:

On 12/12/2012 03:11 PM, Wanderer wrote:

I have a program that has a main GUI and a camera. In the main GUI,
you can manipulate the images taken by the camera. You can also use
the menu to check the camera's settings. Images are taken by the
camera in a separate thread, so the long exposures don't block the
GUI. I block conflicts between the camera snapshot thread and the
main thread by setting a flag called self.cameraActive. I check to
see if the cameraActive flag is false and set the cameraActive to
True just before starting the thread. I generate an event on exiting
the thread which sets the cameraActive flag to False. I also check
and set and reset the flag in all the menu commands that access the
camera. Like this.

  def onProperties(self, event):
  """ Display a message window with the camera properties
  event -- The camera properties menu event
  """
  # Update the temperature
  if not self.cameraActive:
  self.cameraActive = True
  self.camera.getTemperature()
  camDict = self.camera.getPropertyDict()
  self.cameraActive = False
  else:
  camDict = {'Error': 'Camera Busy'}
  dictMessage(camDict, 'Camera Properties')

This works

I don't think so.  in between the if and the assignment, another thread
could get in there and also set the flag.  Then when either one of them
finishes, it'll clear the flag and the other code is unprotected.

For semaphores between multiple threads, you either have to define only
a single thread at any given moment being permitted to modify it, or you
have to use lower-level primitives, sometimes called test+set operation.

i don't know the "right" way to do this in Python, but this isn't it.

but my question is, is there a better way using semaphores, locks or
something else to prevent collisions between threads?

Thanks


if you already have the cameraActive variable reset by an event at
thread termination; it's not necessary to set it false in the menu
command.  It's better NOT to do that. Your GUI menu functions need only
test to see if self.cameraActive is false, and then set it to true just
before the launch of the second thread.  The second thread, itself,
ought never change the cameraActive variable.

I'm also not sure why you are able to obtain the information from the
camera sequentially (camDict?) when you say you are not blocking the GUI.
I  assume self.camera.getTemperature() launches the second thread ?  Is it,
somehow, explicitly allowing the continued processing of GUI events that
accessing the camera straight in the GUI would not allow?

If you are talking about the Python semaphore library, I don't think you
need it.

Semaphores are really for use when multiple threads wish to access a
resource where more than one thread can use the resource at a time;
That would mean multiple threads using the camera at once... not a good
idea.

The Lock() object essentially does the same thing, but assumes only 1
thread may use it at a time; hence that would be sufficient (if it
were needed at all!).

A lock is in the "thread" library (Python 2.xx) or the "threading"
library (Python 3.xx).  Semaphores aren't part of the thread library in
Python 2.xx... (another reason not to bother with them...)

However, Locking will cause the GUI thread to block when the camera is
in use, which isn't what you want -- correct?

There is a way to test the lock but not block, which is equivalent to
your variable (to be honest!);  I'm pretty sure that Python doesn't use
true Posix threads but only the GNU Pth library.  That means that the
only time threads truly switch is determined by the Python interpreter.
In that case, all python variable assignments are going to be effectively
atomic anyhow... and a variable, like you are using, is identical to a lock.
(Atomic merely means the write can't be interrupted by a thread switch partway
through).

If you have a multi-processing environment, there is a multiprocessor
library -- where the lock or semaphore mechanism would be important.
But I really don't think you need it.

 


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


Re: unpacking first few items of iterable

2012-12-13 Thread Terry Reedy

On 12/13/2012 3:09 PM, MRAB wrote:

On 2012-12-13 19:37, Daniel Fetchinson wrote:

Hi folks, I swear I used to know this but can't find it anywhere:

What's the standard idiom for unpacking the first few items of an
iterable whose total length is unknown?


An hinted by some of the answers, this is not a complete specification.


Something like

a, b, c, _ = myiterable

where _ could eat up a variable number of items, in case I'm only
interested in the first 3 items?


The literal answer given by demian, a,b,c,*_=iterable, has some good 
uses but fails on an infinite iterable, and otherwise exhausts iterators 
and creates a potentially long sequence that, by the specification, is 
not needed. Mitya's alternative of slicing, seq[:3] requires a directly 
sliceable sequence rather than just an iterable.



You could do this:

from itertools import islice
a, b, c = islice(myiterable, 3)


This works for any iterable and the only discarded temporary is a 
sequence of three items (needed so either all bindings work or none are 
made).


If you want to bind a default values if iterable has less than 3 values, 
one way is


>>> a,b,c = itertools.islice(itertools.chain(itertools.islice((1,2), 
3), [None]*3), 3)

>>> a,b,c
(1, 2, None)

Perhaps clearer is

>>> a,b,c = [None]*3
>>> it = iter((1,2))
>>> try:
a = next(it)
b = next(it)
c = next(it)
except StopIteration:
pass

>>> a,b,c
(1, 2, None)

This has the advantage that if iterable has more than 3 items, 'it' is 
available to iterate over the rest. This is the standard idiom for 
removing a couple of special items before iterating over the remainder 
(when one does not want the remainder as a concrete list).


--
Terry Jan Reedy

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


Re: Stack_overflow error

2012-12-13 Thread Aung Thet Naing
I'm sorry that I have been away from this issue for a while. 

Yes, I'm working on windows. I need to review the error again so that I could 
rephrase my issue clearly. 

Thanks. 

Aung. 
On Tuesday, November 20, 2012 10:40:42 AM UTC-8, Dieter Maurer wrote:
> Aung Thet Naing  writes:
> 
> 
> 
> > I'm having Stack_overflow exception in _ctypes_callproc (callproc.c). The 
> > error actually come from the:
> 
> >
> 
> >  cleanup:
> 
> > for (i = 0; i < argcount; ++i)
> 
> > Py_XDECREF(args[i].keep);
> 
> >
> 
> > when args[i].keep->ob_refCnt == 1
> 
> 
> 
> Really a stack overflow or a general segmentation violation?
> 
> Under *nix, both are not easy to distinguish -- but maybe, you are
> 
> working with Windows?

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


Python version and svn

2012-12-13 Thread Aung Thet Naing
I'm wondering how I can match the svn versions in bug.python.org to Python 
version (2.7.3) etc? When I downloaded Python source from 
http://www.python.org/download/, I cannot really see the svn version. 

Thanks

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


Re: Python version and svn

2012-12-13 Thread Terry Reedy

On 12/13/2012 4:41 PM, Aung Thet Naing wrote:

I'm wondering how I can match the svn versions in bug.python.org to
Python version (2.7.3) etc? When I downloaded Python source from
http://www.python.org/download/, I cannot really see the svn
version.


I do not know what you mean by svn version. In any case, Python 
development was moved from svn to hg in March, 2011, before all current 
releases, so I am sure they do not have such.


--
Terry Jan Reedy

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


Re: unpacking first few items of iterable

2012-12-13 Thread Peter Otten
Terry Reedy wrote:

> On 12/13/2012 3:09 PM, MRAB wrote:
>> On 2012-12-13 19:37, Daniel Fetchinson wrote:
>>> Hi folks, I swear I used to know this but can't find it anywhere:
>>>
>>> What's the standard idiom for unpacking the first few items of an
>>> iterable whose total length is unknown?
> 
> An hinted by some of the answers, this is not a complete specification.
> 
>>> Something like
>>>
>>> a, b, c, _ = myiterable
>>>
>>> where _ could eat up a variable number of items, in case I'm only
>>> interested in the first 3 items?
> 
> The literal answer given by demian, a,b,c,*_=iterable, has some good
> uses but fails on an infinite iterable, and otherwise exhausts iterators
> and creates a potentially long sequence that, by the specification, is
> not needed. Mitya's alternative of slicing, seq[:3] requires a directly
> sliceable sequence rather than just an iterable.
> 
>> You could do this:
>>
>> from itertools import islice
>> a, b, c = islice(myiterable, 3)
> 
> This works for any iterable and the only discarded temporary is a
> sequence of three items (needed so either all bindings work or none are
> made).
> 
> If you want to bind a default values if iterable has less than 3 values,
> one way is
> 
>  >>> a,b,c = itertools.islice(itertools.chain(itertools.islice((1,2),
> 3), [None]*3), 3)
>  >>> a,b,c
> (1, 2, None)

If something doesn't look natural I usually shuffle around my code a bit. In 
this case I might end up with a helper function:

def work_with_abc(a=None, b=None, c=None, *discarded):
 ...
work_with_abc(*myiterable)

> Perhaps clearer is
> 
>  >>> a,b,c = [None]*3
>  >>> it = iter((1,2))
>  >>> try:
> a = next(it)
> b = next(it)
> c = next(it)
> except StopIteration:
> pass
> 
>  >>> a,b,c
> (1, 2, None)

Or

it = iter(myiterable)
a = next(it, None)
b = next(it, None)
c = next(it, None)

> This has the advantage that if iterable has more than 3 items, 'it' is
> available to iterate over the rest. This is the standard idiom for
> removing a couple of special items before iterating over the remainder
> (when one does not want the remainder as a concrete list).



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


testing

2012-12-13 Thread Steven D'Aprano
Testing testing 1 2 3 4.

I've sent at two posts that appear to have been eaten by the Great Usenet 
Monster. Will this fare any better? Time to find out.


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


Re: Python version and svn

2012-12-13 Thread Ned Deily
In article , Terry Reedy  
wrote:
> On 12/13/2012 4:41 PM, Aung Thet Naing wrote:
> > I'm wondering how I can match the svn versions in bug.python.org to
> > Python version (2.7.3) etc? When I downloaded Python source from
> > http://www.python.org/download/, I cannot really see the svn
> > version.
> I do not know what you mean by svn version. In any case, Python 
> development was moved from svn to hg in March, 2011, before all current 
> releases, so I am sure they do not have such.

In particular, the python.org source downloads (tar, bz2, etc) are just 
extracted source files of a particular snapshot in time with no version 
information.

You can browse the hg repository on the web.  To browse by tags that 
correspond to releases:
 
http://hg.python.org/cpython/tags

To browse the current top of each of the development branches:

http://hg.python.org/cpython/branches

Clicking on a change set id in a particular message in a bugs.python.org 
message should open a web page with the details of that change set.

Or you can use hg (http://mercurial.selenic.com) to download your own 
copy of the source repository which will contain the complete source 
history of all branches:

hg clone http://hg.python.org/cpython

More details here:  http://docs.python.org/devguide/

-- 
 Ned Deily,
 n...@acm.org

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


Python parsing Bluetooth RFCOMM for 9 bytes

2012-12-13 Thread Barry Dick
My data looks like this when it comes from the device (biofeedback device). 
There are 9 bytes in total, and I need to buffer so much, and then poll it for 
new/recent packets. The start packet unfortunately starts with 0x00

So far the only thing I've found that looks like what I want to do is this, but 
I don't know how to implement it. http://code.activestate.com/recipes/408859/


Data:  [002d0270025e00]
Data:  [0001004a0006026547]
Data:  [0002004b000a026343]
Data:  [00]
Data:  [03004f0006025b4a00]
Data:  [046698000802569d00]
Data:  [3002830257f100]
Data:  [01004a000602585400]
Data:  [020048000a025b4e00]
Data:  [03004b0006025b4e00]
Data:  [046698000702579d00]
Data:  [2f027602480e00]
Data:  [01004a0006024b61]
Data:  [0002004a000a025552]
Data:  [0003004b0006025752]
Data:  [00046698000702569e]
Data:  [002c025b025321]
Data:  [00010048000602505e]

My code so far looks like this...

import bluetooth, sys, time, os, binascii, struct;

# Create the client socket
client_socket=BluetoothSocket( RFCOMM )

client_socket.connect(("10:00:E8:AC:4D:D0", 1))

data = ""
try:
while True:
try:
data = client_socket.recv(9)
except bluetooth.BluetoothError, b:
print "Bluetooth Error: ", b

if len(data) > 0:
print "Data:  [%s]" % binascii.hexlify(data)

except KeyboardInterrupt:
#print "Closing socket...",
client_socket.close()
#print "done."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to contribute Unicode General Category encoding/decoding

2012-12-13 Thread Steven D'Aprano
On Thu, 13 Dec 2012 07:30:57 -0800, Pander Musubi wrote:

> I was expecting PyPI. Here is the code, please advise on where to submit
> it:
>   http://pastebin.com/dbzeasyq

If anywhere, either a third-party module, or the unicodedata standard 
library module.


Some unanswered questions:

- when would somebody need this function?

- why is is called "decodeUnicodeGeneralCategory" when it 
  doesn't seem to have anything to do with decoding?

- why is the parameter "sortable" called sortable, when it
  doesn't seem to have anything to do with sorting?


If this is useful at all, it would be more useful to just expose the data 
as a dict, and forget about an unnecessary wrapper function:


from collections import namedtuple
r = namedtuple("record", "other name desc")  # better field names needed!

GC = {
'C' : r('Other', 'Other', 'Cc | Cf | Cn | Co | Cs'),
'Cc': r('Control', 'Control', 
'a C0 or C1 control code'), # a.k.a. cntrl
'Cf': r('Format', 'Format', 'a format control character'),
'Cn': r('Unassigned', 'Unassigned', 
'a reserved unassigned code point or a noncharacter'),
'Co': r('Private Use', 'Private_Use', 'a private-use character'),
'Cs': r('Surrogate', 'Surrogate', 'a surrogate code point'),
'L' : r('Letter', 'Letter', 'Ll | Lm | Lo | Lt | Lu'),
'LC': r('Letter, Cased', 'Cased_Letter', 'Ll | Lt | Lu'),
'Ll': r('Letter, Lowercase', 'Lowercase_Letter', 
'a lowercase letter'),
'Lm': r('Letter, Modifier', 'Modifier_Letter', 'a modifier letter'),
'Lo': r('Letter, Other', 'Other_Letter', 
'other letters, including syllables and ideographs'),
'Lt': r('Letter, Titlecase', 'Titlecase_Letter', 
'a digraphic character, with first part uppercase'),
'Lu': r('Letter, Uppercase', 'Uppercase_Letter', 
'an uppercase letter'),
'M' : r('Mark', 'Mark', 'Mc | Me | Mn '), # a.k.a. Combining_Mark
'Mc': r('Mark, Spacing', 'Spacing_Mark', 
'a spacing combining mark (positive advance width)'),
'Me': r('Mark, Enclosing', 'Enclosing_Mark',
'an enclosing combining mark'),
'Mn': r('Mark, Nonspacing', 'Nonspacing_Mark', 
'a nonspacing combining mark (zero advance width)'),
'N' : r('Number', 'Number', 'Nd | Nl | No'),
'Nd': r('Number, Decimal', 'Decimal_Number', 
'a decimal digit'), # a.k.a. digit
'Nl': r('Number, Letter', 'Letter_Number', 
'a letterlike numeric character'),
'No': r('Number, Other', 'Other_Number',
'a numeric character of other type'),
'P' : r('Punctuation', 'Punctuation',  
'Pc | Pd | Pe | Pf | Pi | Po | Ps'), # a.k.a. punct
'Pc': r('Punctuation, Connector', 'Connector_Punctuation', 
'a connecting punctuation mark, like a tie'),
'Pd': r('Punctuation, Dash', 'Dash_Punctuation', 
'a dash or hyphen punctuation mark'),
'Pe': r('Punctuation, Close', 'Close_Punctuation', 
'a closing punctuation mark (of a pair)'),
'Pf': r('Punctuation, Final', 'Final_Punctuation', 
'a final quotation mark'),
'Pi': r('Punctuation, Initial', 'Initial_Punctuation',
'an initial quotation mark'),
'Po': r('Punctuation, Other', 'Other_Punctuation', 
'a punctuation mark of other type'),
'Ps': r('Punctuation, Open', 'Open_Punctuation',
'an opening punctuation mark (of a pair)'),
'S' : r('Symbol', 'Symbol', 'Sc | Sk | Sm | So'),
'Sc': r('Symbol, Currency', 'Currency_Symbol', 'a currency sign'),
'Sk': r('Symbol, Modifier', 'Modifier_Symbol',
'a non-letterlike modifier symbol'),
'Sm': r('Symbol, Math', 'Math_Symbol', 
'a symbol of mathematical use'),
'So': r('Symbol, Other', 'Other_Symbol', 'a symbol of other type'),
'Z' : r('Separator', 'Separator', 'Zl | Zp | Zs'),
'Zl': r('Separator, Line', 'Line_Separator',
'U+2028 LINE SEPARATOR only'),
'Zp': r('Separator, Paragraph', 'Paragraph_Separator',
'U+2029 PARAGRAPH SEPARATOR only'),
'Zs': r('Separator, Space', 'Space_Separator', 
'a space character (of various non-zero widths)'),
}

del r


Usage is then trivially the same as normal dict and attribute access:

py> GC['Ps'].desc
'an opening punctuation mark (of a pair)'



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


Re: Python parsing Bluetooth RFCOMM for 9 bytes

2012-12-13 Thread MRAB

On 2012-12-14 00:00, Barry Dick wrote:

My data looks like this when it comes from the device (biofeedback device). 
There are 9 bytes in total, and I need to buffer so much, and then poll it for 
new/recent packets. The start packet unfortunately starts with 0x00

So far the only thing I've found that looks like what I want to do is this, but 
I don't know how to implement it. http://code.activestate.com/recipes/408859/


Data:  [002d0270025e00]
Data:  [0001004a0006026547]
Data:  [0002004b000a026343]
Data:  [00]
Data:  [03004f0006025b4a00]
Data:  [046698000802569d00]
Data:  [3002830257f100]
Data:  [01004a000602585400]
Data:  [020048000a025b4e00]
Data:  [03004b0006025b4e00]
Data:  [046698000702579d00]
Data:  [2f027602480e00]
Data:  [01004a0006024b61]
Data:  [0002004a000a025552]
Data:  [0003004b0006025752]
Data:  [00046698000702569e]
Data:  [002c025b025321]
Data:  [00010048000602505e]

My code so far looks like this...

import bluetooth, sys, time, os, binascii, struct;

# Create the client socket
client_socket=BluetoothSocket( RFCOMM )

client_socket.connect(("10:00:E8:AC:4D:D0", 1))

data = ""
try:
while True:
try:
data = client_socket.recv(9)
except bluetooth.BluetoothError, b:
print "Bluetooth Error: ", b

if len(data) > 0:
print "Data:  [%s]" % binascii.hexlify(data)

except KeyboardInterrupt:
#print "Closing socket...",
client_socket.close()
#print "done."


Is the following more like how you want it?

data = ""
try:
while True:
try:
more = client_socket.recv(9)
except bluetooth.BluetoothError, b:
print "Bluetooth Error: ", b
else:
data += more

while len(data) >= 9:
print "Data:  [%s]" % binascii.hexlify(data[ : 9])
data = data[9 : ]
except KeyboardInterrupt:
#print "Closing socket...",
client_socket.close()
#print "done."

You could, of course, decide to recv more than 9 bytes at a time. It
could return less than you asked for (but it should block until at
least 1 byte is available), but it will never return more than you
asked for.
--
http://mail.python.org/mailman/listinfo/python-list


What are the minimum requirements to get a job in?

2012-12-13 Thread suresh . pinnapa
My aim is to get a job into google or cisco or facebok.
I have basic knowledge in python,c,java and good in javascript,html,css, 
database concepts.
If i learn django and python. Shall I get my dream job?

Please suggest me
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: What are the minimum requirements to get a job in?

2012-12-13 Thread Graham Fielding


 
> Date: Thu, 13 Dec 2012 18:49:32 -0800
> Subject: What are the minimum requirements to get a job in?
> From: suresh.pinn...@gmail.com
> To: python-list@python.org
> 
> My aim is to get a job into google or cisco or facebok.
> I have basic knowledge in python,c,java and good in javascript,html,css, 
> database concepts.
> If i learn django and python. Shall I get my dream job?
> 
> Please suggest me
> -- 
> http://mail.python.org/mailman/listinfo/python-list
You'd need a fair bit of industry cred to get picked up at a place like Google, 
I'd imagine.  By all means, keep pursuing your dream, but temper your 
expectations.   -- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread Greg Donald
On Thu, Dec 13, 2012 at 8:49 PM,   wrote:
> My aim is to get a job into google or cisco or facebok.

I made it to the 4th interview with Google.  When they say they want a
"developer" they really mean they want a developer/sysadmin/kernel
hacker/c/c++ guru.  I nailed all the Python questions in interviews #2
and #3, but then at interview #4 they started asking inode questions,
how to implement a compiler, how to design my own version of
memcopy(), etc.  It didn't really matter to them that I had 2M
downloads on Google Play, or that I knew Ruby, Rails, Python, Django,
PHP, iOS and Java..  I didn't know how to move 2GBs of memory from
here to there without using memcopy(), so that was that :(

> I have basic knowledge in python,c,java and good in javascript,html,css,
> database concepts.

My story above was a preface to the fact that "basic knowledge"
usually isn't enough for hot tech companies like Google.  From what I
understand Facebook is becoming more C and less PHP all the time.  And
I imagine they use a lot of C and assembly at Cisco since that's
mostly embedded device work.

> If i learn django and python. Shall I get my dream job?

Doubt it, but good luck all the same :)

> Please suggest me

Visit their job boards.


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


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread Dave Angel
On 12/13/2012 09:49 PM, suresh.pinn...@gmail.com wrote:
> My aim is to get a job into google or cisco or facebok.
> I have basic knowledge in python,c,java and good in javascript,html,css, 
> database concepts.
> If i learn django and python. Shall I get my dream job?
>
> Please suggest me

You didn't say what your dream job is, but I'll assume it's as a
software Engineer.  You also didn't say at what level you expect to start.

There are lots more questions than what you've answered so far.  Like
what degree do you have, and from where?  Can you read/hear and
understand English quickly, both written and verbal?  Can you write
correct English (as opposed to what we see here on the forum)?  Can you
write a good resume, and a great cover letter?

Do you know any one computer language thoroughly?  Or just a little of
many languages?

Have you ever worked in assembly code?  Do you know what a transistor
is?  Have you ever built a compiler or a debugger?  Have you ever
written code that has to run in very little memory (like less than 4k)? 
Have you ever worked on projects where the end result had to have 100%
reliability?  Have you written multithreaded code?  Have you worked on
multiple operating systems?

Have you ever read Knuth?  Or P.J. Plauger?  Or Sedgewick?  Can you
explain (roughly) Huffman encoding?  (I looked up Huffman's paper (I
think it was written in 1952, in IRE) and studied it, about 25 years ago)

Have you ever worked with the public?  Have you ever debugged somebody
else's code that was over 200k LOC?

Do you have good references from past jobs, and are those jobs relevant
to what you hope to be hired to do?  Do you belong to any professional
organizations, did you get any honors in college?  Do you have any
industry honors, either from patents, or from ACM or other recognized
organizations.

Can you point to projects where you've made a substantial and
identifiable contribution, and describe those contributions in terms
that will interest your prospective employer?
 
Are you personable, and can you participate in a debate with someone who
seems to deliberately be trying to trip you up?  If you have opinions or
preferences, can you explain clearly why you have them?  Can you
interact with an interviewer as an equal, respectful but not subservient?

Perhaps most important, have you worked with somebody who really liked
what you do and who now works at one of these companies, in a place
where his recommendation will help?  The best jobs are seldom given to
people who send in a resume blind, or who work through ordinary headhunters.

These and many other questions, plus luck, patience and persistence will
determine whether you get that dream job.

-- 

DaveA

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


Re: MySQLdb compare lower

2012-12-13 Thread Cameron Simpson
On 13Dec2012 18:39, Dennis Lee Bieber  wrote:
| On Thu, 13 Dec 2012 18:00:48 +1100, Cameron Simpson 
| declaimed the following in gmane.comp.python.general:
| > On 12Dec2012 02:03, Dennis Lee Bieber  wrote:
| > |   According to the old "MySQL Language Reference" 
| > | """
| > | By default, string comparisons are not case sensitive and will use the
| > | current character set (ISO-8859-1 Latin1 by default, which also works
| > | excellently for English).
| > | """
| > 
| > I'm flabbergasted. [... consults the internets ...] It is still the case
| > today:-( Ouch.
| >
|   I just checked... The book I referenced was the blue&white published
| by the late MySQL AB -- and the book claims to cover up to v5.0.1... I
| thought it was just the end of the 4.x branch (like the old brown
| O'Reilly/MySQL AB book was middle era of 4.x)

My checking was for MySQL 5.5. Still case insensitive.
-- 
Cameron Simpson 

'Soup: This is the one that Kawasaki sent out pictures, that looks so beautiful.
Yanagawa: Yes, everybody says it's beautiful - but many problems!
'Soup: But you are not part of the design team, you're just a test rider.
Yanagawa: Yes. I just complain.
- _Akira Yanagawa Sounds Off_ @ www.amasuperbike.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread Dave Angel
On 12/13/2012 10:33 PM, Dave Angel wrote:
> On 12/13/2012 09:49 PM, suresh.pinn...@gmail.com wrote:
>> My aim is to get a job into google or cisco or facebok.
>> I have basic knowledge in python,c,java and good in javascript,html,css, 
>> database concepts.
>> If i learn django and python. Shall I get my dream job?
>>
>> Please suggest me
> You didn't say what your dream job is, but I'll assume it's as a
> software Engineer.  You also didn't say at what level you expect to start.
>
> There are lots more questions than what you've answered so far.  Like
> what degree do you have, and from where?  Can you read/hear and
> understand English quickly, both written and verbal?  Can you write
> correct English (as opposed to what we see here on the forum)?  Can you
> write a good resume, and a great cover letter?
>
> Do you know any one computer language thoroughly?  Or just a little of
> many languages?
>
> Have you ever worked in assembly code?  Do you know what a transistor
> is?  Have you ever built a compiler or a debugger?  Have you ever
> written code that has to run in very little memory (like less than 4k)? 
> Have you ever worked on projects where the end result had to have 100%
> reliability?  Have you written multithreaded code?  Have you worked on
> multiple operating systems?
>
> Have you ever read Knuth?  Or P.J. Plauger?  Or Sedgewick?  Can you
> explain (roughly) Huffman encoding?  (I looked up Huffman's paper (I
> think it was written in 1952, in IRE) and studied it, about 25 years ago)
>
> Have you ever worked with the public?  Have you ever debugged somebody
> else's code that was over 200k LOC?
>
> Do you have good references from past jobs, and are those jobs relevant
> to what you hope to be hired to do?  Do you belong to any professional
> organizations, did you get any honors in college?  Do you have any
> industry honors, either from patents, or from ACM or other recognized
> organizations.
>
> Can you point to projects where you've made a substantial and
> identifiable contribution, and describe those contributions in terms
> that will interest your prospective employer?
>  
> Are you personable, and can you participate in a debate with someone who
> seems to deliberately be trying to trip you up?  If you have opinions or
> preferences, can you explain clearly why you have them?  Can you
> interact with an interviewer as an equal, respectful but not subservient?
>
> Perhaps most important, have you worked with somebody who really liked
> what you do and who now works at one of these companies, in a place
> where his recommendation will help?  The best jobs are seldom given to
> people who send in a resume blind, or who work through ordinary headhunters.
>
> These and many other questions, plus luck, patience and persistence will
> determine whether you get that dream job.
>

I should have pointed out that there's no need to have 100% on these. 
But there will be a similar list for any good job, and each hiring
manager will have some things which are just plain mandatory.  But most
important is that you can discuss intelligently what you have done, and
what you do know.  I've been hired in several positions where I didn't
match the "requirements" in the least, but talked them into it anyway. 
And I've turned down at least one job when I discovered they wanted me
for what I already knew.

It used to be that if you could just get any job at a company, you could
eventually earn your way into the perfect spot.  But that's frequently
not true anymore.

You also should spend some serious energy trying to decide what your
perfect job would be like.  I once gave 49 subordinates to a new person
i hired, and stepped into a new position for which I wrote the HR job
description.  It was either that or take on 30 more, and I didn't want
to manage any more.  I was working for over 20 years before the first
time I ever wanted my boss' job.  And I got over that quickly.





-- 

DaveA

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


What are the minimum requirements to get a job in?

2012-12-13 Thread michaelsafyan
Hi, Suresh. I don't know about the hiring practices at Cisco or Facebook, but 
at Google, the particular language or technology matters far less in an 
interview than general coding ability, algorithmic understanding, and system 
design fundamentals. To be sure, Python is an awesome language to learn (if I 
didn't think so, I would not have subscribed to this mailing list) and Django 
is quite useful, but my advice to you would be to gain as much practical 
experience writing code as possible and to really solidify your understanding 
of algorithms, data structures, and analysis of their runtime and memory 
performance.

You can find out more about jobs at Google at http://jobs.google.com/

- Michael Safyan
http://gplus.to/michaelsafyan

P.S. Responding just as myself; not an official Google response.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb compare lower

2012-12-13 Thread Chris Angelico
On Fri, Dec 14, 2012 at 2:35 PM, Cameron Simpson  wrote:
> On 13Dec2012 18:39, Dennis Lee Bieber  wrote:
> | On Thu, 13 Dec 2012 18:00:48 +1100, Cameron Simpson 
> | declaimed the following in gmane.comp.python.general:
> | > On 12Dec2012 02:03, Dennis Lee Bieber  wrote:
> | > |   According to the old "MySQL Language Reference"
> | > | """
> | > | By default, string comparisons are not case sensitive and will use the
> | > | current character set (ISO-8859-1 Latin1 by default, which also works
> | > | excellently for English).
> | > | """
> | >
> | > I'm flabbergasted. [... consults the internets ...] It is still the case
> | > today:-( Ouch.
> | >
> |   I just checked... The book I referenced was the blue&white published
> | by the late MySQL AB -- and the book claims to cover up to v5.0.1... I
> | thought it was just the end of the 4.x branch (like the old brown
> | O'Reilly/MySQL AB book was middle era of 4.x)
>
> My checking was for MySQL 5.5. Still case insensitive.

Yeah, it's one of the things that tripped me up when I did a
MySQL->PostgreSQL conversion earlier this year. The code was assuming
case insensitivity, and began failing on PG. Fortunately the simple
change of LIKE to ILIKE solved that.

I'd MUCH rather be explicit about wanting case insensitivity. I wonder
who would go insane first if I ran an app using Wine under Linux in a
directory that's mounted via cifs from a Windows or OS/2 box... (And
yes, I have that setup, ready to go. Only there's an extra level of
indirection - I'd run it in an sshfs mount that points to my proxy
box. Extra safety, keeps messy networking away from my real boxes.)

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


Re: OOP noob question: Mixin properties

2012-12-13 Thread Steven D'Aprano
On Thu, 13 Dec 2012 16:20:51 -0800, Micky Hulse wrote:

> Learning things here...
> 
> In my mixin class (a version I wrote for Django) I had this (indentation
> removed for better list readability):

Indentation is important. Please don't remove it. I've added it back in 
below:

> class JSONResponseMixin(object):
> def __init__(self):
> self._cache = False
> self._cache_timeout = 86400
> self._cache_key = None
> @property
> def cache(self):
> return self._cache
> @cache.setter
> def cache(self, value):
> self._cache = value
> @cache.deleter
> def cache(self):
> del self._cache
[...]

The use of @property here doesn't give you any benefit (except, maybe, if 
you are paid by the line of code). Better to just expose the "cache" 
attribute directly, and likewise for the others. If, in the future, you 
need to turn them into computed properties, you can easily do so. But for 
now:

class JSONResponseMixin(object):
def __init__(self):
self.cache = False
self.cache_timeout = 86400
self.cache_key = None

and you're done.


[...]
> ...which works! But, then I looked here:
> 
> 
> 
> Simply doing this:

> class JSONResponseMixin(object):
> cache = False
> cache_timeout = 86400 # 24 hours.
> cache_key = None

> ...works just as good! Not to mention, it's less verbose.

Yes. But keep in mind that there is a slight difference between what you 
have here and what I suggested above.

In my code above, the cache attributes are defined on a per-instance 
basis. Each instance will have its own set of three cache* attributes. In 
the version directly above, there is a single set of cache* attributes 
shared by all JSONResponseMixin instances.

Will this make any practical difference? Probably not. Most importantly, 
if you write:

instance = Api()  # class includes JSONResponseMixin
instance.cache = True

then the assignment to an attribute will create a non-shared per-instance 
attribute which overrides the class-level shared attribute. This is 
almost certainly the behaviour that you want. So this is a good example 
of using class attributes to implement shared default state.

There is one common place where the use of shared class attributes can 
lead to surprising results: if the class attribute is a mutable object 
such as a list or a dict, it may not behave the way you expect. That is 
because only *assignment* creates a new per-instance attribute:

instance.attribute = "spam spam spam"  # overrides the class attribute


while modifying the attribute in place does not:

instance.shared_list.append("spam spam spam") 
# every instance of the class will now see the change


Apart from that Gotcha, the use of shared class attributes to implement 
default behaviour is perfectly acceptable.


> I guess I wanted to run my ideas by the Python gurus just to make sure I
> was not doing crazy stuff here...

Seems fine to me.



> The above seems better than taking the more functional approach:
> 
> return self.render_to_response(data, cache, cache_timeout, cache_key)
> 
> Then again, maybe the more functional approach is better for its
> simplicity?

I actually prefer a functional response, up to the point where I'm 
passing so many arguments to functions that I can't keep track of what's 
what. Then I refactor into a class.


> Hopefully I'm not boring ya'll to death. :D

No worries :-)



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


Running a python script under Linux

2012-12-13 Thread Steven D'Aprano
I understand this is not exactly a Python question, but it may be of 
interest to other Python programmers, so I'm asking it here instead of a 
more generic Linux group.

I have a Centos system which uses Python 2.4 as the system Python, so I 
set an alias for my personal use:

[steve@ando ~]$ which python
alias python='python2.7'
/usr/local/bin/python2.7


When I call "python some_script.py" from the command line, it runs under 
Python 2.7 as I expected. So I give the script a hash-bang line:

#!/usr/bin/env python

and run the script directly, but instead of getting Python 2.7, it runs 
under Python 2.4 and gives me system errors.

When I run env directly, it ignores my alias:

steve@ando ~]$ /usr/bin/env python -V
Python 2.4.3


What am I doing wrong?


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


Re: Running a python script under Linux

2012-12-13 Thread Cameron Simpson
On 14Dec2012 02:45, Steven D'Aprano  
wrote:
| I understand this is not exactly a Python question, but it may be of 
| interest to other Python programmers, so I'm asking it here instead of a 
| more generic Linux group.
| 
| I have a Centos system which uses Python 2.4 as the system Python, so I 
| set an alias for my personal use:
| 
| [steve@ando ~]$ which python
| alias python='python2.7'
| /usr/local/bin/python2.7
| 
| 
| When I call "python some_script.py" from the command line, it runs under 
| Python 2.7 as I expected. So I give the script a hash-bang line:
| 
| #!/usr/bin/env python
| 
| and run the script directly, but instead of getting Python 2.7, it runs 
| under Python 2.4 and gives me system errors.
| 
| When I run env directly, it ignores my alias:
| 
| steve@ando ~]$ /usr/bin/env python -V
| Python 2.4.3
| 
| 
| What am I doing wrong?

You're assuming aliases are exported. They are not. (I've seen ksh
present exportable aliases, but IMO it is a bad idea anyway.)

You're (slightly) better off putting a python symlink in /usr/local/bin, but
that may break arbitrary other things (as, indeed, would your #! incantation
were it effective). Also a bad idea though.

Regarding aliases, I would make a "py27" alias for my personal typing
convenience perhaps, but _not_ try to make the command "python" run
anything but the system default python (24, as you say).

When I need a particular minimum revision of python I use one of my
"py25+", "py26+", "py27+", "py30+" etc wrapper scripts. Code for "py25+"
here:

  https://bitbucket.org/cameron_simpson/css/src/tip/bin/py25+

This has the advantages of not conflicting with a system name like
"python" and also is usable with your #! incantation, which requires an
executable file after "env".

Cheers,
-- 

Carpe Datum - John Sloan 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python parsing Bluetooth RFCOMM for 9 bytes

2012-12-13 Thread Barry Dick

> Is the following more like how you want it?
> 
> 
> 
> data = ""
> 
> try:
> 
>  while True:
> 
>  try:
> 
>  more = client_socket.recv(9)
> 
>  except bluetooth.BluetoothError, b:
> 
>  print "Bluetooth Error: ", b
> 
>  else:
> 
>  data += more
> 
> 
> 
>  while len(data) >= 9:
> 
>  print "Data:  [%s]" % binascii.hexlify(data[ : 9])
> 
>  data = data[9 : ]
> 
> except KeyboardInterrupt:
> 
>  #print "Closing socket...",
> 
>  client_socket.close()
> 
>  #print "done."
> 
> 
> 
> You could, of course, decide to recv more than 9 bytes at a time. It
> 
> could return less than you asked for (but it should block until at
> 
> least 1 byte is available), but it will never return more than you
> 
> asked for.

Thank you for your interest and quick reply. 

Its a great start, seeing as I'm a beginner with python, I was actually hoping 
to see an example of http://code.activestate.com/recipes/408859/ as it appears 
to be exactly what I need, but I haven't got a clue how to implement it. 
Basically as each byte perhaps gets read or 9 bytes at a time, that way I can 
seek out as much real data as possible

Data:  [002c025b025321]
Data:  [00010048000602505e]
Data:  [0002004a000a025552]
Data:  [0003004b0006025752]
Data:  [00046698000702569e]

(notice the header data[9:1] will always flow in this pattern 0 -> 4 and then 
back again, so I figure that might as well be my start)


And skip the errors...

Data:  [0002004b000a026343]
Data:  [00]
Data:  [03004f0006025b4a00]
Data:  [046698000802569d00]
Data:  [3002830257f100]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb compare lower

2012-12-13 Thread Frank Millman

On 14/12/2012 06:16, Chris Angelico wrote:


Yeah, it's one of the things that tripped me up when I did a
MySQL->PostgreSQL conversion earlier this year. The code was assuming
case insensitivity, and began failing on PG. Fortunately the simple
change of LIKE to ILIKE solved that.

I'd MUCH rather be explicit about wanting case insensitivity.


Just as a side-note, for those who may be interested -

PostgreSQL allows you to create an index using an expression.

Therefore you can say -

  CREATE INDEX ndx ON table_name (LOWER(col_name))

Then you can SELECT ... WHERE LOWER(col_name) = LOWER(%s), and it will 
use the index, so it is not necessary to coerce the data to lower case 
before storing.


Frank Millman


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


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread rusi
On Dec 14, 8:33 am, Dave Angel  wrote:
> Do you know any one computer language thoroughly?  Or just a little of
> many languages?

There is a quote by Bruce Lee to the effect:
I am not afraid of the man who knows 10,000 kicks
I am afraid of the man who has practised 1 kick 10,000 times
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread Devin Jeanpierre
On Fri, Dec 14, 2012 at 1:13 AM, rusi  wrote:
> On Dec 14, 8:33 am, Dave Angel  wrote:
>> Do you know any one computer language thoroughly?  Or just a little of
>> many languages?
>
> There is a quote by Bruce Lee to the effect:
> I am not afraid of the man who knows 10,000 kicks
> I am afraid of the man who has practised 1 kick 10,000 times

It's worth pointing out that kicks stay relevant for your entire life.
Unfortunately, many programming languages don't.

I guess the next metaphor would be stock investments and
diversification. Point is, don't just practice one kick.

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


Re: Running a python script under Linux

2012-12-13 Thread Andrew Robinson

On 12/13/2012 06:45 PM, Steven D'Aprano wrote:

I understand this is not exactly a Python question, but it may be of
interest to other Python programmers, so I'm asking it here instead of a
more generic Linux group.

I have a Centos system which uses Python 2.4 as the system Python, so I
set an alias for my personal use:

[steve@ando ~]$ which python
alias python='python2.7'
 /usr/local/bin/python2.7


When I call "python some_script.py" from the command line, it runs under
Python 2.7 as I expected. So I give the script a hash-bang line:

#!/usr/bin/env python

and run the script directly, but instead of getting Python 2.7, it runs
under Python 2.4 and gives me system errors.

When I run env directly, it ignores my alias:

steve@ando ~]$ /usr/bin/env python -V
Python 2.4.3


What am I doing wrong?



After seeing the lecture on Bad Ideas ... this might backfire on me :)

But ... if you really want to make the alias show up in all bash shells, 
you can put it in your ~/.bashrc file which is executed every time a 
shell is created.

alias python='python2.7'

However, alias expansions do not work in non-interactive shells -- so I 
don't think it will launch with the #!/bin/env technique.


OTOH -- Shell functions DO operate in non-interactive mode, so you could 
add something like:


function python() {
python3 # whichever version of python you want as default
}
# eof of function example to add to ~/.bashrc

OR
In a bash shell, you can also do:

function python {
python3 # or 2.7 ...
}
export -f python

And that would give the same effect as an alias, but funtions can be 
exported to child processes.


It's your system, and we're adults here -- screw it up however you want to.
Cheers!








--
--Jesus Christ is Lord.

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


Re: Running a python script under Linux

2012-12-13 Thread Jussi Piitulainen
Steven D'Aprano writes:

> I have a Centos system which uses Python 2.4 as the system Python, so I 
> set an alias for my personal use:
> 
> [steve@ando ~]$ which python
> alias python='python2.7'
> /usr/local/bin/python2.7
> 
> 
> When I call "python some_script.py" from the command line, it runs under 
> Python 2.7 as I expected. So I give the script a hash-bang line:
> 
> #!/usr/bin/env python
> 
> and run the script directly, but instead of getting Python 2.7, it runs 
> under Python 2.4 and gives me system errors.
> 
> When I run env directly, it ignores my alias:
> 
> steve@ando ~]$ /usr/bin/env python -V
> Python 2.4.3

The alias is known only to the shell for which it is defined. The
shell does nothing with it when it occurs in an argument position. So
env receives just the six-letter string "python" which it resolves as
a program name by walking the file system along your PATH until it
finds the program.

Why not just set your PATH so that the python that is python2.7 is
found first. If this breaks something, your alias would also have
broken that something if aliases worked the way you wanted. Try.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a python script under Linux

2012-12-13 Thread Andrew Robinson

On 12/13/2012 06:45 PM, Steven D'Aprano wrote:

What am I doing wrong?


By the way,  I didn't include command line parameters as part of the 
function definition, so you might want to add them to insure it acts 
like a generic alias.


Also, (alternately), you could define a generic python shell 
script/import with the duty of checking for a compatible python version; 
and if the wrong one is executing --  it could then import the shell 
command execution function, and *fork* the correct version of python on 
the script; then it could exit.


... or whatever ;)


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


Re: Python parser problem

2012-12-13 Thread Paul Rudin
Chris Angelico  writes:

> On Fri, Dec 14, 2012 at 6:12 AM, RCU  wrote:
>>   Dave,
>> Thanks for the reply.
>> The script was originally edited on Windows with proper \r\n endings,
>
> It's worth noting that many Windows-based editors and interpreters are
> quite happy with \n line endings. You may be able to save yourself
> some trouble by switching everything to Unix newlines.

... and in particular emacs for windows works well.

(holy wars ensue...)

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


Re: What are the minimum requirements to get a job in?

2012-12-13 Thread rusi
On Dec 14, 11:56 am, Devin Jeanpierre  wrote:
> On Fri, Dec 14, 2012 at 1:13 AM, rusi  wrote:
> > On Dec 14, 8:33 am, Dave Angel  wrote:
> >> Do you know any one computer language thoroughly?  Or just a little of
> >> many languages?
>
> > There is a quote by Bruce Lee to the effect:
> > I am not afraid of the man who knows 10,000 kicks
> > I am afraid of the man who has practised 1 kick 10,000 times
>
> It's worth pointing out that kicks stay relevant for your entire life.
> Unfortunately, many programming languages don't.
>
> I guess the next metaphor would be stock investments and
> diversification. Point is, don't just practice one kick.
>
> -- Devin

Then again its worth pointing out that there is difference between
programming and (a) programming language.  If that were not so the
whole idea of a 'degree' in computer 'science' that is by implication
on par with other sciences would be completely bogus.

That academic computer science gets its act more wrong than right is a
different question:
http://blog.languager.org/2011/02/cs-education-is-fat-and-weak-1.html

The point of those posts is that this is the current state of CS
education; however that is not necessary condition.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python parser problem

2012-12-13 Thread Chris Angelico
On Fri, Dec 14, 2012 at 6:30 PM, Paul Rudin  wrote:
> Chris Angelico  writes:
>
>> On Fri, Dec 14, 2012 at 6:12 AM, RCU  wrote:
>>>   Dave,
>>> Thanks for the reply.
>>> The script was originally edited on Windows with proper \r\n endings,
>>
>> It's worth noting that many Windows-based editors and interpreters are
>> quite happy with \n line endings. You may be able to save yourself
>> some trouble by switching everything to Unix newlines.
>
> ... and in particular emacs for windows works well.
>
> (holy wars ensue...)

So do lots of others. In fact, the only editor I've seen that
consistently fails is Notepad.

Actually... that sentence stands alone. The only editor I've seen that
consistently fails is Notepad.

(holy wars are deflected into heaping scorn on an Acceptable Target)

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