Re: Why do Perl programmers make more money than Python programmers

2013-05-07 Thread Benjamin Kaplan
On May 7, 2013 5:42 PM, "Neil Hodgson"  wrote:
>
> jmfauth:
>
>> 2) More critical, Py 3.3, just becomes non unicode compliant,
>> (eg European languages or "ascii" typographers !)
>> ...
>
>
>This is not demonstrating non-compliance. It is comparing performance,
not compliance.
>
>Please show an example where Python 3.3 is not compliant with Unicode.
>
>Neil
> --
> http://mail.python.org/mailman/listinfo/python-list

It's violating page 1+1j of the Unicode spec, where it says precisely how
long each operation is allowed to take. Only wise people can see that page.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: in need of some help regarding my rock paper scissors game

2013-05-12 Thread Benjamin Kaplan
On Sun, May 12, 2013 at 12:33 PM, Alex Norton  wrote:
> im new to python and im in the middle of making a RPS game for a college
> unit.
>
> i have used PyQt to create the GUI and i have received help regarding adding
> the code to the buttons.
>
> but its missing something as the error
>
> 'Traceback (most recent call last): File "C:\Users\Me\Desktop\testy.py",
> line 174, in bWater.clicked.connect( water_clicked ) AttributeError: 'int'
> object has no attribute 'clicked'' appears when i run the module.
>
> i was wondering if somebody could walk me through making the game complete
> and to add the results of the game (win/lose/stalemate) to the loutcome
> label
>
>  attached is the game file.
>
> --

bWater is an int. Integers don't have a clicked attribute. So
bWater.clicked.connect(water_clicked) looks for the clicked attribute
of the integer bWater, can't find it, and throws an error. Also,
Python scripts are executed line by line- at the time you make that
call, the water_clicked function doesn't exist yet, so even if that
was the correct call, it wouldn't work here.

I haven't used PyQT before so I can't say what the correct way to set
this up would be, but that's at least what's causing this error.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python #ifdef

2013-05-28 Thread Benjamin Kaplan
On May 28, 2013 1:10 PM, "Carlos Nepomuceno" 
wrote:
>
> Thank you! I made it run like the following. What do you think about
that? IS there a better way?
>
>
>
> #The following runs on Python 2.7
> sc3='''
> # Python 3
> def original(n):
> m = 0
> for b in n.to_bytes(6, 'big'):
> m = 256*m + b
> return m
> '''
> if sys.version_info[0] == 3:
> exec(sc3)
> --

No need for exec.

if sys.version_info[0] >= 3:
def original(n) :
   ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-using copyrighted code

2013-06-08 Thread Benjamin Kaplan
On Sat, Jun 8, 2013 at 2:31 PM, Malte Forkel  wrote:
> Hello,
>
> I have written a small utility to locate errors in regular expressions
> that I want to upload to PyPI.  Before I do that, I would like to learn
> a litte more about the legal aspects of open-source software. What would
> be a good introductory reading?
>
> Plus, I have one very specific question: In my package, I use modified
> code from sre_parse.py, which is part of the Python release. That file
> has the following header:
>
> #
> # Secret Labs' Regular Expression Engine
> #
> # convert re-style regular expression to sre pattern
> #
> # Copyright (c) 1998-2001 by Secret Labs AB.  All rights reserved.
> #
> # See the sre.py file for information on usage and redistribution.
> #
>
> The referenced information is missing in the version of sre.py that
> comes with current versions of Python, but I found it in the archive
> http://effbot.org/media/downloads/sre-2.2.1.zip. It reads:
>
> #
> # Secret Labs' Regular Expression Engine
> #
> # re-compatible interface for the sre matching engine
> #
> # Copyright (c) 1998-2001 by Secret Labs AB.  All rights reserved.
> #
> # This version of the SRE library can be redistributed under CNRI's
> # Python 1.6 license.  For any other use, please contact Secret Labs
> # AB (i...@pythonware.com).
> #
> # Portions of this engine have been developed in cooperation with
> # CNRI.  Hewlett-Packard provided funding for 1.6 integration and
> # other compatibility work.
> #
>
> Now, how am I supposed to deal with that? Ask Secret Labs for some kind
> of permission? Leave it as it is and add my own copyright line?
>
> Malte
>

You can find the license terms for all versions of Python at
http://docs.python.org/3/license.html
I'm not a lawyer, but it looks like you just need to include the
copyright statement.

I'm not sure why the sre stuff is still licensed under the 1.6
license. Did no one get permission to distribute it under the PSF
license, or did no one bother to rewrite the comment in the file?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-09 Thread Benjamin Kaplan
On Sun, Jun 9, 2013 at 2:38 AM, Νικόλαος Κούρας  wrote:
> Τη Κυριακή, 9 Ιουνίου 2013 12:20:58 μ.μ. UTC+3, ο χρήστης Lele Gaifax έγραψε:
>
>> > How about a string i wonder?
>> > s = "νίκος"
>> > what_are these_bytes = s.encode('iso-8869-7').encode(utf-8')
>
>> Ignoring the usual syntax error, this is just a variant of the code I
>> posted: "s.encode('iso-8869-7')" produces a bytes instance which
>> *cannot* be "re-encoded" again in whatever encoding.
>
> s = 'a'
> s = s.encode('iso-8859-7').decode('utf-8')
> print( s )
>
> a (we got the original character back)
> 
> s = 'α'
> s = s.encode('iso-8859-7').decode('utf-8')
> print( s )
>
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 0: 
> unexpected end of data
>
> Why this error? because 'a' ordinal value > 127 ?
> --

No. You get that error because the string is not encoded in UTF-8.
It's encoded in ISO-8859-7. For ASCII strings (ord(x) < 127),
ISO-8859-7 and UTF-8 look exactly the same. For anything else, they
are different. If you were to try to decode it as ISO-8859-1, it would
succeed, but you would get the character "á" back instead of α.

You're misunderstanding the decode function. Decode doesn't turn it
into a string with the specified encoding. It takes it *from* the
string with the specified encoding and turns it into Python's internal
string representation. In Python 3.3, that encoding doesn't even have
a name because it's not a standard encoding. So you want the decode
argument to match the encode argument.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-09 Thread Benjamin Kaplan
On Sun, Jun 9, 2013 at 2:20 AM, Νικόλαος Κούρας  wrote:
> Τη Κυριακή, 9 Ιουνίου 2013 12:12:36 μ.μ. UTC+3, ο χρήστης Cameron Simpson 
> έγραψε:
>> On 09Jun2013 02:00, =?utf-8?B?zp3Or866zr/PgiDOk866z4EzM866?= 
>>  wrote:
>>
>> | Steven wrote:
>>
>> | >> Since 1 byte can hold up to 256 chars, why not utf-8 use 1-byte for
>>
>> | >> values up to 256?
>>
>> |
>>
>> | >Because then how do you tell when you need one byte, and when you need
>>
>> | >two? If you read two bytes, and see 0x4C 0xFA, does that mean two
>>
>> | >characters, with ordinal values 0x4C and 0xFA, or one character with
>>
>> | >ordinal value 0x4CFA?
>>
>> |
>>
>> | I mean utf-8 could use 1 byte for storing the 1st 256 characters. I meant 
>> up to 256, not above 256.
>>
>>
>>
>> Then it would not be UTF-8. UTF-8 will encode an Unicode codepoint. Your 
>> >suggestion will not.
>
> I dont follow.
>

The point in the UTF formats is that they can encode any of the 1.1
million codepoints available in Unicode. Your suggestion can only
encode 256 code points. We have that encoding already- it's called
Latin-1 and it can't encode any of your Greek characters (hence why
ISO-8859-7 exists, which can encode the Greek characters but not the
Latin ones).

If you were to use the whole byte to store the first 256 characters,
you wouldn't be able to store character number 256 because the
computer wouldn't be able to tell the difference between character 257
(0x01 0x01) and two chr(1)s. UTF-8 gets around this by reserving the
top bit as a "am I part of a multibyte sequence" flag,

>> | >> UTF-8 and UTF-16 and UTF-32
>>
>> | >> I though the number beside of UTF- was to declare how many bits the
>>
>> | >> character set was using to store a character into the hdd, no?
>>
>> |
>>
>> | >Not exactly, but close. UTF-32 is completely 32-bit (4 byte) values.
>>
>> | >UTF-16 mostly uses 16-bit values, but sometimes it combines two 16-bit
>>
>> | >values to make a surrogate pair.
>>
>> |
>>
>> | A surrogate pair is like itting for example Ctrl-A, which means is a 
>> combination character that consists of 2 different characters?
>>
>> | Is this what a surrogate is? a pari of 2 chars?
>>
>>
>>
>> Essentially. The combination represents a code point.
>>
>>
>>
>> | >UTF-8 uses 8-bit values, but sometimes
>>
>> | >it combines two, three or four of them to represent a single code-point.
>>
>> |
>>
>> | 'a' to be utf8 encoded needs 1 byte to be stored ? (since ordinal = 65)
>>
>> | 'α΄' to be utf8 encoded needs 2 bytes to be stored ? (since ordinal is > 
>> 127 )
>>
>> | 'a chinese ideogramm' to be utf8 encoded needs 4 byte to be stored ? 
>> (since ordinal >  65000 )
>>
>> |
>>
>> | The amount of bytes needed to store a character solely depends on the 
>> character's ordinal value in the Unicode table?
>>
>>
>>
>> Essentially. You can read up on the exact process in Wikipedia or the 
>> Unicode Standard.
>
>
>
> When you say essentially means you agree with my statements?
> --

In UTF-8 or UTF-16, the number of bytes required for the character is
dependent on its code point, yes. That isn't the case for UTF-32,
where every character uses exactly four bytes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-using copyrighted code

2013-06-09 Thread Benjamin Kaplan
On Sun, Jun 9, 2013 at 1:32 PM, Mark Janssen  wrote:
> On Sun, Jun 9, 2013 at 12:50 PM, Michael Torrie  wrote:
>> On 06/09/2013 11:18 AM, Mark Janssen wrote:
>>> You actually do not.  Attaching a legal document is purely a secondary
>>> protection from those who would take away right already granted by US
>>> copyright.
>>
>> You are correct, except that the OP has already stated he wishes to have
>> his code distributed. Without granting a license, the code cannot be
>> distributed beyond the people he personally gives the code too.  PyPi
>> cannot legally allow others to download it without a license.
>
> That's not entirely correct.  If he *publishes* his code (I'm using
> this term "publish" technically to mean "put forth in a way where
> anyone of the general public can or is encouraged to view"), then he
> is *tacitly* giving up protections that secrecy (or *not* disclosing
> it) would *automatically* grant.  The only preserved right is
> authorship after that.   So it can be re-distributed freely, if
> authorship is preserved.  The only issue after that is "fair use" and
> that includes running the program (not merely copying the source).
>

No, the original author retains all rights except those explicitly
granted. The same way that obtaining the "source" to a song does not
give you the right to redistribute the song all you want.

> Re-selling for money violates fair-use, as does redistribution without
> preserving credit assignment (unless they've naively waived those
> rights away).  I will have to take a look at  PyPi.  But if you are
> *publishing*, there's no court which can protect your IP afterwards
> from redistribution, unless you explicitly *restrict* it.  In which
> case, if you restrict terms of re-use, you're putting the court in
> jeopardy because you making two actions opposed to one another.  The
> only thing the court can easily uphold is your authorship and
> non-exploitation from a violation of fair-use (note again the key word
> is "use", nor merely copying the code).  But then if you waive *that*
> right away, you put the court in jeopardy again.
>

Fair use has nothing to do with money. It depends on how the work is
used and how you've changed it. Weird Al's song parodies are fair use,
even though he sells them. You distributing copies of a commercial
software to everyone is not fair use, even though you aren't making
money.

>> Here's how the GPL puts it, and of course this applies to any and all
>> licenses, even proprietary ones:
>>
>> "However, nothing else [besides the License] grants you permission to
>> modify or distribute the Program or its derivative works. These actions
>> are prohibited by law if you do not accept this License. Therefore, by
>> modifying or distributing the Program (or any work based on the
>> Program), you indicate your acceptance of this License to do so, and all
>> its terms and conditions for copying..."
>
> Well this is where one must make a distinction with fair-use -- if I
> re-publish my modifications then the code is still subject to the
> terms by the original author.  If I make a copy for myself and run the
> problem for personal, non-commercial use, then I am in the domain of
> fair use and have no other obligations.
>

Again, no. The GPL does not restrict your rights when running on
machines you control, but that's just because of the terms of the
license. Most commercial licenses include terms like "no reverse
engineering the software" that have nothing to do with distribution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-using copyrighted code

2013-06-09 Thread Benjamin Kaplan
On Sun, Jun 9, 2013 at 6:40 PM, Mark Janssen  wrote:
>> Mark, ever watched TV? Or gone to the movies? Or walked into a bookshop?
>> Listened to the radio? All these things publish copyrighted work. It is
>> utter nonsense that merely publishing something in public gives up the
>> monopoly privileges granted by copyright.
>
> That's not correct.  Keep in mind, that the law is for people:  there
> is no automatic right to profit.  There certainly is no "right to
> monopoly" (which you are absurdly arguing) on *anything* released to
> the public.  If you want that monopoly *you* have to provide the means
> to protect your IP.  You, sir, are being ridiculous and perhaps the
> court along with you -- I'm just telling you what is correct.  That's
> important.
>
> A movie producer, publishes his/her work as soon as he/she puts it on
> the market or otherwise releases it for public viewing.  That's just
> the risk of doing business.  Fortunately, for them, its not easy to
> make a verbatim copy of a film, in a theatre or otherwise.   But
> copyright ensures that they get the credit for making the movie -- not
> for profit of publishing it.
>
> Now copyright includes the clause of "fair-use", so that means one can
> make a copy of something if they aren't depriving the original creator
> of legitimate gains.  If they are truly depriving the creator(s) of
> legit gains, then they are in violation.  That's all the law should
> support.  Don't think there is any law that can determine, once and
> for all, what counts as "legitimate gains" and what violates "fair
> use".   *You* have simply *sold out*.   "Legitimate gains" is
> something the courts have to work out, on a case-by-case basis, but if
> the movie producers are that worried about losing their gains, then
> they can do the f-ing work and require movie goers to sign a simple
> clause promising that they won't try to copy the movie (on concealed
> cameras and such).
>



The fact that a work is non commercial is one of several factors that
is taken into account when determining fair use. It is not an
automatic fair use for non-commercial works. I have no idea where your
understanding of copyright law came from, but here is the relevant
section of the US legal code:

17 USC § 107 - Limitations on exclusive rights: Fair use
Notwithstanding the provisions of sections 106 and 106A, the fair use
of a copyrighted work, including such use by reproduction in copies or
phonorecords or by any other means specified by that section, for
purposes such as criticism, comment, news reporting, teaching
(including multiple copies for classroom use), scholarship, or
research, is not an infringement of copyright. In determining whether
the use made of a work in any particular case is a fair use the
factors to be considered shall include—
(1) the purpose and character of the use, including whether such use
is of a commercial nature or is for nonprofit educational purposes;
(2) the nature of the copyrighted work;
(3) the amount and substantiality of the portion used in relation to
the copyrighted work as a whole; and
(4) the effect of the use upon the potential market for or value of
the copyrighted work.
The fact that a work is unpublished shall not itself bar a finding of
fair use if such finding is made upon consideration of all the above
factors.


Can you provide any citations for your interpretation? Besides "that's
what the law should be", I mean.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Version Control Software

2013-06-13 Thread Benjamin Kaplan
On Jun 13, 2013 10:17 AM, "Grant Edwards"  wrote:
>
> On 2013-06-13, Ben Finney  wrote:
> > cutems93  writes:
> >
> >> I am looking for an appropriate version control software for python
> >> development, and need professionals' help to make a good decision.
> >
> >> Currently I am considering four software: git, SVN, CVS, and
> >> Mercurial.
> >
> > These days there is no good reason to use CVS nor Subversion for new
> > projects. They are not distributed (the D in DVCS), and they have
> > specific design flaws that often cause insidious problems with common
> > version control workflows. As a salient example, branching and merging
> > are so painful with these tools that many users have learned the
> > terrible habit of never doing it at all.
>
> I agree that branch/merge handling in svn is primitive compared to git
> (haven't used hg enough to comment).
>
> The last time we made the choice (4-5 years ago), Windows support for
> get, bzr, and hg was definitely lacking compared to svn.  The lack of
> something like tortoisesvn for hg/git/bzr was a killer.  It looks like
> the situation has improved since then, but I'd be curious to hear from
> people who do their development on Windows.
>

There's a TortoiseHg now that works well. http://tortoisehg.bitbucket.org

I haven't used it very much, but github has released a git client for
Windows.  The underlying library is the same one Microsoft uses for the
Visual Studio git integration, so I assume it's fairly robust at this point.
http://windows.github.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eval of expr with 'or' and 'and' within

2013-06-14 Thread Benjamin Kaplan
On Jun 14, 2013 9:34 AM, "Michael Torrie"  wrote:
>
> On 06/14/2013 03:50 AM, Nick the Gr33k wrote:
> >  >>> print(name or month or year)
> > abcd
> >  >>> print(name and month and year)
> > ijkl
>
> Interesting.  I'd have thought a boolean expression would return True or
> False, not a string.  Learn something new every day.
>
>
>

Python didn't have a Boolean type for quite some time (2.2?). Until then,
True and False were ints. Since every object had a Boolean value, you
didn't need to turn the result into an integer. In an "and" clause, python
returns the first false value or the last value, because that will evaluate
to the correct Boolean value. In an "or" clause, python returns the first
true value or the last value. When Python finally got a Boolean type, no
one wanted to break backwards compatibility for this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables versus name bindings [Re: A certainl part of an if() structure never gets executed.]

2013-06-17 Thread Benjamin Kaplan
On Mon, Jun 17, 2013 at 8:55 AM, Simpleton  wrote:
> On 17/6/2013 5:22 μμ, Terry Reedy wrote:
>>
>> On 6/17/2013 7:34 AM, Simpleton wrote:
>>>
>>> On 17/6/2013 9:51 πμ, Steven D'Aprano wrote:

 Now, in languages like Python, Ruby, Java, and many others, there is no
 table of memory addresses. Instead, there is a namespace, which is an
 association between some name and some value:

 global namespace:
  x --> 23
  y --> "hello world"
>>>
>>>
>>> First of all thanks for the excellent and detailed explanation Steven.
>>>
>>> As for namespace:
>>>
>>> a = 5
>>>
>>> 1. a is associated to some memory location
>>> 2. the latter holds value 5
>>
>>
>> This is backwards. If the interpreter puts 5 in a *permanent* 'memory
>> location' (which is not required by the language!), then it can
>> associate 'a' with 5 by associating it with the memory location. CPython
>> does this, but some other computer implementations do not.
>
>
> Please tell me how do i need to understand the sentence
> 'a' is being associated with number 5 in detail.
>
> Why don't we access the desired value we want to, by referencing to that
> value's memory location directly instead of using namespaces wich is an
> indirect call?
>
> i feel we have 3 things here
>
> a , memory address of a stored value, actual stored value
>
>>> So is it safe to say that in Python a == &a ? (& stands for memory
>>> address)
>>>
>>> is the above correct?
>>
>>
>> When you interpret Python code, do you put data in locations with
>> integer addresses?
>
>
> I lost you here.
>

You're confusing the way in which the CPython interpreter is written
with the way the Python language is defined. Yes, the CPython
interpreter puts 5 into a numbered memory location when creating the
object. But the Nikos Python Interpreter (which is a completely valid,
although quite buggy, Python interpreter that uses your head to
interpret the code) should not be using numbered memory locations.

Forget about memory locations. Memory locations don't exist. Let's use
the pen-and-paper Python interpreter. On the left side of the paper,
we'll write down the names. On the rest of the paper, we'll write down
the objects.

When I do "x =[]", I make a new list (which means I write down []
somewhere in the middle of the page), I create the name "x" (which
means I write down an "x" on the left side of the page), and then I
draw an arrow pointing from the x to the [].
(sorry if my drawing doesn't line up in your email/news client- I'll
try to make it line up correctly with a monospace font)

|  x --> []|
|  |
|  |


Now, When we do y = x, the right side of the equation is evaluated
(which gives us the object currently bound to the name x) and it is
then given the newly created name "y"

|  x --> []|
| ^|
|   y ||


When we do x.append(3), the object that x refers to is modified. This
is seen by both x and y because they point to the same object.


|  x --> [3]   |
| ^|
|   y ||


When I do x = [], a new object is created somewhere else on the page,
and the name x is made to point to the new object. This changes the
arrow. The name "x" is not in any way tied to the location of the [3]
on the page. This doesn't impact "y" which is still pointing at the
same spot it was before


|  x >[] [3]   |
| ^|
|   y ||


That is how Python's object model works. In CPython, objects have
specified memory locations but names do not. In IronPython and Jython,
even that's not guaranteed- the garbage collector can move the objects
around during their lifetime, so while you can trust that a name will
always point to the correct object, you have no guarantee about where
the object is located in the computer's memory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this PEP-able? fwhile

2013-06-24 Thread Benjamin Kaplan
On Mon, Jun 24, 2013 at 8:54 PM, Chris Angelico  wrote:
> On Tue, Jun 25, 2013 at 12:01 PM, rusi  wrote:
>> On Tuesday, June 25, 2013 3:08:57 AM UTC+5:30, Chris Angelico wrote:
>>> On Tue, Jun 25, 2013 at 5:52 AM,  <> wrote:
>>>
>>> > (NOTE:  Many people are being taught to avoid 'break' and 'continue' at 
>>> > all
>>> > costs...
>>>
>>> Why? Why on earth should break/continue be avoided?
>>
>> Because breaks and continues are just goto-in-disguise?
>>
>> [Well so is while and if and function-call and... Who is to say that?]
>
> And that's still not a reason imho. You've just pointed out that
> they're all control-flow. :)
>
> ChrisA

The reason I was given (which I promptly ignored, of course) is that
it's "best practice" to only have one exit point for a block of code.
Only one way of terminating your loop, only one "return" per function,
never use exceptions, etc. I think it originally came about as a way
to make sure that your clean-up code was called (and to make it easier
for code reviewers to make sure your clean up code was called) and
then started being passed around as a rule among programming teachers
who didn't have any experience outside the classroom.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell Script to use pythonw.exe ?

2013-07-03 Thread Benjamin Kaplan
On Jul 3, 2013 8:27 AM, "Νίκος"  wrote:
>
> Στις 3/7/2013 6:43 πμ, ο/η Tim Roberts έγραψε:
>
>> goldtech  wrote:
>>>
>>>
>>> I just changed the file extension of the script file from .py to .pyw
>>> and it uses pythonw.exe. I didn't read it anywhere, just intuited it
>>> and tried it. Python has some very smart people working the language...
>>
>>
>> While your statement is true, that's not what happened here.
>>
>> Windows has long had the ability to associate a file extension with a
>> handler.  If you start a command shell, the "assoc" command tells you the
>> program type associated with an extension, and the "ftype" command tells
>> you the command line that will be executed for that program type.  On my
>> box:
>>
>> C:\tmp>assoc .py
>> .py=Python
>>
>> C:\tmp>ftype Python
>> Python="C:\Apps\Python27\Python.exe" "%1" %*
>>
>> C:\tmp>assoc .pyw
>> .pyw=Python.NoConFile
>>
>> C:\tmp>ftype Python.NoConFile
>> Python.NoConFile="C:\Apps\Python27\Pythonw.exe" "%1" %*
>>
>> You can create your own, if you want.  If you want files with a .script
>> extension to run PythonW, you can type:
>>
>>  assoc .script=Python.NoConFile
>>
> My associations are broken, bt i only care for open web pages with Chrome
instead of IE, so i sued your method:
>
>
> C:\Windows\system32>assoc .html=Chrome
> .html=Chrome
>
> C:\Windows\system32>ftype
Chrome="C:\Users\Ferrous\AppData\Local\Google\Chrome\Application\chrome.exe"
%1
>
>
Chrome="C:\Users\Ferrous\AppData\Local\Google\Chrome\Application\chrome.exe"
%1
>
> but still when i click a link IE keeps popping up isntead of Chrome.
> Any ideas why?

Because your links don't open files. They send requests to an http server
for data. And IE is the program designated to send http requests. Just use
the browser's "make this the default" button.
> --
> What is now proved was at first only imagined
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing modules into IronPython

2013-07-03 Thread Benjamin Kaplan
On Wed, Jul 3, 2013 at 3:05 PM, HighBeliever  wrote:
> Hi, I have to shift a Python 2.7 program to run in Windows. Doing that has 
> forced me to use IronPython because my program is dependent on a .dll file 
> that uses .NET framework.
>
> I moved all my code to Iron Python and modified it to work with the dll. But 
> I cant import PyQt4 module into the project. Is there a way I can do that? 
> Please Help.
> --

Generally, extensions that aren't pure Python can only be used with
the interpreter they were designed for. There has been some attempt to
get CPython extensions working under IronPython (there's a tracking
issue on IronPython's bug tracker-
http://ironpython.codeplex.com/workitem/11333), but I don't know how
well it works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte

2013-07-05 Thread Benjamin Kaplan
On Jul 5, 2013 12:12 AM, "Lele Gaifax"  wrote:
>
> Νίκος Gr33k  writes:
>
> > try:
> >   host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0]
> > except Exception as e:
> >   host = "Reverse DNS Failed"
> >
> > How can the above code not be able to reeverse dns any more and it
> > falls back to  the failed string?
>
> The only way to know is actually printing out the exception, either to
> stderr, or better using the logging facility, as I suggested.
>
> FYI, your code above is (almost) exactly equivalent to the simpler
>
> try:
> host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0]
> except:
> host = "Reverse DNS Failed"
>
> ciao, lele.
>

They aren't equivalent. "except Exception" won't catch KeyboardInterrupt or
SystemExit or a few others that you really don't want to catch in a generic
error handler. You should almost never have a bare except.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explain your acronyms (RSI?)

2013-07-06 Thread Benjamin Kaplan
On Sat, Jul 6, 2013 at 12:38 PM, Terry Reedy  wrote:
> "rms has crippling RSI" (anonymous, as quoted by Skip).
>
> I suspect that 'rms' = Richard M Stallman (but why lower case? to insult
> him?). I 'know' that RSI = Roberts Space Industries, a game company whose
> Kickstarter project I supported. Whoops, wrong context. How about 'Richard
> Stallman Insanity' (his personal form of megalomania)? That makes the phrase
> is a claim I have read others making.
>
> Lets continue and see if that interpretation works. "should indicate that
> emacs' ergonomics is not right". Aha! Anonymous believes that using his own
> invention, emacs, is what drove Richard crazy. He would not be the first
> self invention victim.
>
> But Skip mentions 'worse for wrists'. So RSI must be a physical rather than
> mental condition. Does 'I' instead stand for Inoperability?, Instability?,
> or what?
>
> Let us try Google. Type in RSI and it offers 'RSI medications' as a choice.
> Sound good, as it will eliminate all the companies with those initials. The
> two standard medical meanings of RSI seem to be Rapid Sequence Intubation
> and Rapid Sequence Induction. But those are procedures, not chronic
> syndromes. So I still do not know what the original poster, as quoted by
> Skip, meant.
>
> --
> Terry Jan Reedy

RSI is a repetitive stress injury.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GeoIP2 for retrieving city and region ?

2013-07-15 Thread Benjamin Kaplan
On Sat, Jul 13, 2013 at 10:43 AM, Νικόλας  wrote:
> Στις 13/7/2013 7:54 μμ, ο/η Dennis Lee Bieber έγραψε:
>>
>> Are you paying for a fixed IP number? I suspect you are if you
>> were
>> running a world-accessible server.
>>
>> Obviously a fixed IP will be tied to a fixed connection and
>> thereby to
>> a fixed location which can be provided to a location database.
>>
>> But most of us have DHCP assigned IP numbers, which change
>> everytime we
>> reboot our connection (or even when the DHCP lease expires -- which may be
>> daily).
>
>
> Same networking scheme for me too, dynamic that is.
>
> Every time the DHCP lease expires or i reboot the router i get a new ip
> address but every time the link i provided states accurately that my ip
> address is from Thessaloníki and not Europe/Athens which is were my ISP
> location is.
>
> Not to mention that in facebook, no matter the way i'am joining, via
> smartphone, tablet, laptop it always pinpoints my exact location.
>
> But yes, i can understand your skepticism.
> An ip address can move anywhere while remaining connected to the same ISP,
> just like a networking device in the house, remains connected to the same
> router while changing rooms or even floors, or even buildings.
>
> But then how do you explain the fact that
> http://www.maxmind.com/en/geoip_demo
> pinpointed Thessaloníki and not Athens and for 2 friends of mine that use
> the same ISP as me but live in different cities also accurately identified
> their locations too?
>

It's not telling you where your ISP is headquartered. It's telling you
where the servers that you're connecting to are. In your case, you're
connecting to servers that your Athens-based ISP has in a Thessaloniki
datacenter. The only way to get an accurate location is to use
something other than IP- phones like to use a combination of their
GPS, a map of the cell phone towers, and a map of wi-fi hotspots (this
is one of the things that Google's StreetView cars log as they drive).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read STDIN as bytes rather than a string

2012-06-18 Thread Benjamin Kaplan
On Mon, Jun 18, 2012 at 4:13 PM, Jason Friedman  wrote:
> I tried this:
>
> Python 3.2.2 (default, Feb 24 2012, 20:07:04)
> [GCC 4.6.1] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import sys
 import io
 fh = io.open(sys.stdin)
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: invalid file: <_io.TextIOWrapper name='' mode='r'
> encoding='UTF-8'>
 fh = io.open(sys.stdin, "rb")
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: invalid file: <_io.TextIOWrapper name='' mode='r'
> encoding='UTF-8'>
> --

You want to read from sys.stdin.buffer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "constant sharing" works differently in REPL than in script ?

2012-06-18 Thread Benjamin Kaplan
On Mon, Jun 18, 2012 at 7:52 PM,   wrote:
> Listening to 'Radio Free Python' episode 8 
> (http://radiofreepython.com/episodes/8/ - around about the 30 minute mark) I 
> heard that Python pre creates some integer constants to avoid a proliferation 
> of objects with the same value.
>
> I was interested in this and so I decided to try it out.
>
> First I did this at the prompt :
>
 c = 1
 print id(1)
> 26906152
 print id(c)
> 26906152
 c is 1
> True
>
> So that matched what I'd heard and then I did this to test the limits of it :
>
 c = 259
 print id(259)
> 26167488
 print id(c)
> 26167512
 c is 259
> False
>
> And that was reasonable too as the podcast mentioned it was only done for a 
> small set of integers around zero.
>
> However when I wrote this script :
>
> c = 259
> print id(259)
> print id(c)
> if c is 259:
>    print "%s - yes" % (c)
> else:
>    print "%s - no " % (c)
>
> I got this output :
>
> C:\data\src\Python\foo>python untitled-2.py
> 26760884
> 26760884
> 259 - yes
>
> So what's going on here. The script seems to be sharing objects in a way the 
> REPL isn't ?
>
> Can anyone explain please ?
>
> BTW this is all on : Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC 
> v.1500 32 bit (Intel)] on win32 .
>

Python the language doesn't specify anything about this sort of
behavior. CPython the implementation does all sorts of optimizations
to make code run more efficiently. Caching integers is one of those
optimizations. In the case where the code is compiled all at once (as
in the script) instead of one line at a time (the REPL), it can do
more optimizations. But as I said, none of this is in the
specification so you shouldn't rely on it. The general rule for the
"is" operator is that unless you specifically know that you need it,
don't use it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: None shown in output

2012-06-21 Thread Benjamin Kaplan
On Thu, Jun 21, 2012 at 8:42 PM, Xander Solis  wrote:
> Hello Python list,
>
> Noob here with a newbie question. I'm reading and working on the exercise of
> the book, Learn Python the Hard way 2.0. When I use this code, I get "None"
> on the output. My question is why does this happen?
>
> def get_numbers(first_num, second_num, operator):
>
>     if operator == 'add':
>         print first_num + second_num
>     elif operator == 'minus':
>         print first_num - second_num
>     elif operator == 'divide':
>         print first_num / second_num
>     elif operator == 'multiply':
>         print first_num * second_num
>
> print "%r" % (get_numbers(1, 2, 'minus'))
> print "%r" % (get_numbers(1+3, 2+9, 'add'))
> print "%r" % (get_numbers(10, 2, 'divide'))
>
> Output:
>
> C:\code\python>ex19.py
> -1
> None
> 15
> None
> 5
> None
> 7.5
>
> --
>
> Thanks in advance for your help.
>
> Regards,
>
> Xander
>

printing something just writes the value to th
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: None shown in output

2012-06-21 Thread Benjamin Kaplan
damn

On Thu, Jun 21, 2012 at 9:24 PM, Benjamin Kaplan
 wrote:
> On Thu, Jun 21, 2012 at 8:42 PM, Xander Solis  wrote:
>> Hello Python list,
>>
>> Noob here with a newbie question. I'm reading and working on the exercise of
>> the book, Learn Python the Hard way 2.0. When I use this code, I get "None"
>> on the output. My question is why does this happen?
>>
>> def get_numbers(first_num, second_num, operator):
>>
>>     if operator == 'add':
>>         print first_num + second_num
>>     elif operator == 'minus':
>>         print first_num - second_num
>>     elif operator == 'divide':
>>         print first_num / second_num
>>     elif operator == 'multiply':
>>         print first_num * second_num
>>
>> print "%r" % (get_numbers(1, 2, 'minus'))
>> print "%r" % (get_numbers(1+3, 2+9, 'add'))
>> print "%r" % (get_numbers(10, 2, 'divide'))
>>
>> Output:
>>
>> C:\code\python>ex19.py
>> -1
>> None
>> 15
>> None
>> 5
>> None
>> 7.5
>>
>> --
>>
>> Thanks in advance for your help.
>>
>> Regards,
>>
>> Xander
>>
>
> printing something just writes the value to th

I hate when I accidentally hit send early. Anyway, Michael already
gave you the reason- print and return two different things.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-25 Thread Benjamin Kaplan
On Mon, Jun 25, 2012 at 11:19 AM, David Thomas  wrote:
> Hello,
> This is my first post so go easy on me.  I am just beginning to program using 
> Python on Mac.  When I try to execute a file using Python Launcher my code 
> seems to cause an error in terminal, when I execute the exact same piece of 
> code and run it in windows it seems to execute as exactly intended.
>  How can I make my python script to open up correctly using Python Launcher?  
> I am running 10.7 on my Mac.  I would upload a photo with the error I get but 
> I can't seem to find the upload feature in this group.
>
> Thanks
> --

You can't find the upload feature because this isn't a Google Group.
It's a Usenet newsgroup that Google Groups provides access to that's
also available as a mailing list. If you want to provide an image, use
an image host and link to the image.

As to your question, I have a few questions of my own. What version of
Python are you using? Is it the version included in Mac OS X,
installed from a python.org binary, compiled by source, or installed
through a package manager? What happens if you call the script from
the command line instead of using the Launcher application?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl __DATA__ construct.

2012-06-25 Thread Benjamin Kaplan
On Mon, Jun 25, 2012 at 2:20 PM, Mladen Gogala  wrote:
> I have a script in Perl that I need to rewrite to Python. The script
> contains __DATA__ at the end of the script, which enables Perl to access
> all the data after that through a file descriptor, like this:
>
> usage() if ( !$stat or !defined($home) or !defined($base) or !defined
> ($sid) );
> while () {
>    s/%OB/$base/;
>    if ( length($home) > 0 ) {
>        s/%OH/$home/;
>    }
>    else {
>        s/\/%OH$//;
>    }
>    if ( length($sid) > 0 && /%OS/ ) {
>        s/%OS/$sid/;
>    }
>    elsif (/%OS/) {
>        next;
>    }
>    s/%VR/$ver/;
>    print;
> }
> __DATA__
> # .bashrc
> # Source global definitions
> if [ -f /etc/bashrc ]; then
>        . /etc/bashrc
> fi
> set -a
>
> # User specific aliases and functions
> export PATH=/sbin:/bin:/usr/sbin:$PATH
> export EDITOR=vi
> export ORACLE_BASE=%OB
> export ORACLE_HOME=$ORACLE_BASE/product/%VR/%OH
> export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/opt/odbc/lib:$ORACLE_HOME/lib32
> export CLASSPATH=/opt/java/lib/tools.jar:$ORACLE_HOME/jdbc/lib/
> ojdbc14.jar:.
>
> ..
>
>
>
> How do I do the same thing in Python? Alternatively, in Perl I can put an
> entire file into a string by using something like:
>
> $str=< This is all a single string,
> no matter how many lines do
> I put in it, but I do have to
> escape the special character
> EOF
> ;
>
> Is there a way to do the same thing in Python? The idea of the script is
> to generate $HOME/.bashrc for any automagically provisioned Oracle
> installation.
>
either escape the new-line
'hello \
world'

or use triple-quoted strings
"""hello
world"""

http://docs.python.org/tutorial/introduction.html#strings
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-26 Thread Benjamin Kaplan
On Tue, Jun 26, 2012 at 10:19 AM, David Thomas  wrote:
> I have installed Python 2.7.3 from Python.org also in Terminal it states that 
> I have 2.7.3.
> How can I execute the script from Terminal?  I've tried typing python into 
> the window and then dragging the file to terminal but I get a syntax error.  
> Sorry I am new to Python and just want to know how I can open such a file 
> using 10.7.
>
> Thanks
>
> http://www.freeimagehosting.net/ilbqt
> http://www.freeimagehosting.net/r5ars

My guess would be that you're getting a SyntaxError when you run it
through the Launcher too. WIthout seeing the script, I don't know why
that would is.

I can tell you one thing you're doing wrong. Never, ever, use input()
in Python 2. If you do, all someone has to do is type in
__import__('os').remove(__file__) and stuff starts getting deleted.
"input" interprets what it reads in. Use raw_input() instead, which
always returns a string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to decode String using unknown codec?

2012-06-27 Thread Benjamin Kaplan
On Wed, Jun 27, 2012 at 6:14 PM,   wrote:
> Hi
> I'm a Korean and when I use modules like sys, os, &c,
> sometimes the interpreter show me broken strings like
> '\x13\xb3\x12\xc8'.
> It mustbe the Korean "alphabet" but I can't decode it to the rightway.
> I tried to decode it using codecs like cp949,mbcs,utf-8
> but It failed.
> The only way I found is eval('\x13\xb3\x12\xc8').
> It raises an Error with showing right Korean.
> Is there any way to deal it being not broken?
> --

It's not broken. You're just using the wrong encodings. Try utf-16le.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: moving methods from class to instance of other class

2012-06-28 Thread Benjamin Kaplan
On Wed, Jun 27, 2012 at 11:59 PM, lars van gemerden
 wrote:
> Hi all,
>
> I have some trouble with the following question: Let say i have the
> following classes:
>
> class A(object):
>    def __init__(self):
>        self.name = 'a'
>    def do(self):
>        print 'A.do: self.name =', self.name
>
> class B(object):
>    def __init__(self):
>        self.name = 'b'
>
>
>
> The question is: How do i move the 'do' method from A to b (resulting
> in  printing "A.do: self.name = b")?
>
> I have tried (with a = A() and b  B()):
>
> B.do = types.MethodType(A.do, b) #Error
>
> and stuff like:
>
> b.do = a.do
> b.do()
>
> But either i get an error or b.do() prints  "A.do: self.name = a", so
> the self parameter of a.do is stored somehow in the method.
>
> In other words, how do i unbind 'do' from a/A and bind it to b (the
> instance)?
>
> Cheers, Lars
>

Is there any particular reason you can't just have B be a subclass of
A? You could do

b.do = types.MethodType(A.do.im_func, b, B)

but there's no point in re-inventing the wheel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to compile pygtk in python2.7?

2012-07-07 Thread Benjamin Kaplan
On Sat, Jul 7, 2012 at 9:47 PM, contro opinion  wrote:
> 1.download  pygtk
>
> 2.cd /home/tiger/pygtk-2.24.0
>
> 3.PYTHON=/usr/bin/python2.7  ./configure --prefix=/usr
> 4. make
> 5. make install
>
> tiger@ocean:~$ python2.7
> Python 2.7.3 (default, Jul  1 2012, 14:13:18)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import gtk
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named gtk

>
>  i can't compile pygtk in python2.7,how to compile it?
>
> --

What is the output of make and make install? Does it compile
successfully, or is there an error? Does the current user have
permission to write to /usr?

You haven't given us enough information to figure out what's going on?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help

2012-07-19 Thread Benjamin Kaplan
On Jul 19, 2012 4:04 PM, "Miriam Gomez Rios" 
wrote:
>
> Hello, sorry for bothering you, but I have a doubt,
>
> Is there a way to turn this string into a tuplelist??, I need it for
gurobi
>
>
('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),('per1','persona1.1','pro4'),('per1','persona1.1','pro5'),('per2','persona2.1','pro1'),('per2','persona2.1','pro2'),('per2','persona2.1','pro3'),('per2','persona2.1','pro4'),('per2','persona2.1','pro5'),('per2','persona2.2','pro1'),('per2','persona2.2','pro2'),('per2','persona2.2','pro3'),('per2','persona2.2','pro4'),('per2','persona2.2','pro5'),('per2','persona2.3','pro1'),('per2','persona2.3','pro2'),('per2','persona2.3','pro3'),('per2','persona2.3','pro4'),('per2','persona2.3','pro5'),('per2','persona2.4','pro1'),('per2','persona2.4','pro2'),('per2','persona2.4','pro3'
>
> the string is made with fors, using data from another file, and I need it
as a tuplelist
>
> Thank you
>
>
> --

It looks like you can just put brackets around it and call ast.literal_eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I thought I understood how import worked...

2012-08-07 Thread Benjamin Kaplan
On Aug 7, 2012 8:41 AM, "Roy Smith"  wrote:
>
> On Tuesday, August 7, 2012 9:55:16 AM UTC-4, Ben Finney wrote:
>
> >  The tutorial is misleading on this. It it says plainly:
> >
> > A module can contain executable statements as well as function
> > definitions. […] They are executed only the *first* time the module
> > is imported somewhere.
> >
> > http://docs.python.org/tutorial/modules.html>
>
> That's more than misleading.  It's plain wrong.  The example I gave
demonstrates the "print __file__" statement getting executed twice.
>
> The footnote to that is wrong too:
>
> > [1]   In fact function definitions are also ‘statements’ that are
‘executed’; the execution of a
> > module-level function enters the function name in the module’s global
symbol table.
>
> I think what it's supposed to say is "... the execution of a module-level
def statement ..."
>
> > Care to file a documentation bug http://bugs.python.org/>
> > describing this?
>
> Sure, once I understand how it's really supposed to work :-)
>
> --

Each module only gets imported once. But if the same module can be accessed
as two different names, python doesn't recognize that they are the same
module. Along the same lines, if you create a symlink to the file, you'll
be able to import the same module twice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idle no longer works

2012-08-11 Thread Benjamin Kaplan
On Sat, Aug 11, 2012 at 4:09 PM, Opap-OJ  wrote:
> I can no longer open the Idle IDE for Python on Windows 7.
>
> For 3-5 years I used Idle for all my python work.  But in January this 
> happens:
>
> When I right click on a python file and choose "open with Idle" nothing 
> happens.
>
> If I double-click on the file itself, it briefly opens an MS-DOS looking 
> window, then closes it immediately.
>
> I tried installing Eclipse with PyDev.  It opens the file, but will not run 
> it in Python.
>
> Any idea why?
> --

Have you tried launching Python from the Command Prompt? Open up
command prompt and run C:\Python32\python.exe or whatever corresponds
to your version of Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to fix error "Requires python(abi)=2.4"

2012-08-14 Thread Benjamin Kaplan
On Aug 14, 2012 4:51 AM, "sagarnikam123"  wrote:
>
> i am installing numpy on fedora with python 2.6,2.7 & 3.1
>
>
>
> --

Python bytecode and C interface are not compatible across versions. If
you're trying to install a numpy binary that was compiled against 2.4, it
won't work with newer versions. You either need to find binaries compiled
against a version of python you have or compile numpy yourself
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert base 10 to base 2?

2012-08-20 Thread Benjamin Kaplan
On Mon, Aug 20, 2012 at 12:50 AM,   wrote:
> Hi,
> as you can argue from the subject, i'm really,really new to python.
> What is the best way to achieve that with python? Because the syntax 
> int('30',2) doesn't seem to work!

That syntax goes the other way- from a string representing a number in
the given base into an integer (which doesn't have a base, although
it's stored in base 2).

You get the binary by doing bin(x), where x is an integer.

>>> bin(12)
'0b1100'

If you want to go from a string in base-10 to a string in base-2, you
have to do the conversion to integer first.

>>> bin(int('5',10))
'0b101'

Although you don't need to specify the 10 because that's the default.
>>> bin(int('5'))
'0b101'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen4 - get exit status

2012-08-27 Thread Benjamin Kaplan
On Aug 27, 2012 3:47 PM, "Tim Johnson"  wrote:
>
> In bash I do the following:
> linus:journal tim$ /home/AKMLS/cgi-bin/perl/processJournal-Photo.pl hiccup
> -bash: /home/AKMLS/cgi-bin/perl/processJournal-Photo.pl: No such file or
directory
> linus:journal tim$ echo $?
> 127
>
> In python, use os.popen4 I do the following:
> >>> fin,fout =
os.popen4('/home/AKMLS/cgi-bin/perl/processJournal-Photo.pl hiccup;echo $?')
> >>> results = fout.readlines()
> >>> results
> ['/bin/sh: /home/AKMLS/cgi-bin/perl/processJournal-Photo.pl: No such file
or directory\n', '127\n']
>
> Well, I got the exit code as the last item in the results, but I'm
wondering if
> there is a better way. From help(os) - I don't find any variables
dedicated to
> holding exit status.
>
> Any ideas?
> thanks
> --
> Tim
> tim at tee jay forty nine dot com or akwebsoft dot com
> http://www.akwebsoft.com

The popen* functions are deprecated. You should use the subprocess module
instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is implemented with id ?

2012-09-04 Thread Benjamin Kaplan
On Tue, Sep 4, 2012 at 11:30 PM, Franck Ditter  wrote:
> Hi !
> a is b <==> id(a) == id(b) in builtin classes.
> Is that true ?
> Thanks,
>
> franck

No. It is true that if a is b then id(a) == id(b) but the reverse is
not necessarily true. id is only guaranteed to be unique among objects
alive at the same time. If objects are discarded, their ids may be
reused even though the objects are not the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why did the WindowsError occur?

2012-09-04 Thread Benjamin Kaplan
On Tue, Sep 4, 2012 at 11:30 PM, Levi Nie  wrote:
> my code:
> import os
> os.startfile(r'C:\Program Files\Internet Explorer.exe')
>
> the error:
> os.startfile(r'C:\Program Files\Internet Explorer.exe')
> WindowsError: [Error 2] : 'C:\\Program Files\\Internet Explorer.exe'
>

There's no such thing as C:\Program Files\Internet Explorer.exe. You
probably want C:\Program Files\Internet Explorer\iexplore.exe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing dll

2012-09-06 Thread Benjamin Kaplan
On Sep 6, 2012 8:15 AM, "Helpful person"  wrote:
>
> I am a complete novice to Python.  I wish to access a dll that has
> been written to be compatible with C and VB6.  I have been told that
> after running Python I should enter  "from ctypes import *" which
> allows Python to recognize the dll structure.  I have placed the dll
> into my active directory (if that's the correct word, one on my path)
> for simplification.
>
> I tried:   "import name.dll" but this just gave me an error telling me
> that there was no such module.
>
> Can someone please help?
>
> Richard
> --

Two things:

1) you would never use import name.dll, just like you don't use "import
math.py" you would just import name. But that only works for Python
libraries, which brings us to number 2

2) importing ctypes doesn't work any magic. Your c library is still a c
library, not a python library. Ctypes provides functions to let you load a
dll and makes calls to it, but you can't interact with the dll like python
code. Doing that takes a lot more work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any difference between print 3 and print '3' in Python ?

2012-09-10 Thread Benjamin Kaplan
On Sun, Sep 9, 2012 at 11:33 PM, Dwight Hutto  wrote:
>
>
> On Sun, Sep 9, 2012 at 10:41 AM, Ian Foote  wrote:
>>
>> On 09/09/12 14:23, iMath wrote:
>>>
>>> 在 2012年3月26日星期一UTC+8下午7时45分26秒,iMath写道:

 I know the print statement produces the same result when both of these
 two instructions are executed ,I just want to know Is there any difference
 between print 3 and print '3' in Python ?
>>>
>>> thx everyone
>>
>>
>
> Here's a future import though I used,so I can use the planned 3 with a 2x
> python version in the command line interpreter:
>
> Microsoft Windows [Version 6.1.7600]
> Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
>
> C:\Users\david>c:\python26\python.exe
> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
> on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 exit()
>
> C:\Users\david>c:\python27_64\python.exe
> Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on
> win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
 import __future__
 x = 3
 y = '3'
 print(x)
> 3
 print(y)
> 3

 type(x)
> 
 type(y)
> 
>
 z = '%i' % (3)
 type(z)
> 

>
> In other words type(value), and find out the difference.
> --
> Best Regards,
> David Hutto
> CEO: http://www.hitwebdevelopment.com
>

Somewhat OT, but __future__ doesn't work like that. You have to import
the specific features you want to use.

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print 3
3
>>> import __future__
>>> print 3
3
>>> from __future__ import print_function
>>> print 3
  File "", line 1
print 3
  ^
SyntaxError: invalid syntax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: where's the new python gone?

2012-09-10 Thread Benjamin Kaplan
On Sun, Sep 9, 2012 at 11:10 PM, Dwight Hutto  wrote:
>
> I have several installations on my windows, so I use
> c:\python27_64\python.exe module_file.py
>
> or
>
> c:\python26\python.exe module_file.py
>
> in the command line.
>
>
> Not to show that this shouldn't be a discussion, but usually it's searching.
> Here's search term a link, and some python docs:
>
> install python windows command line
>
> or click:
>
> https://www.google.com/search?q=install+python+windows+command+line&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-ahere's
>
> and one of the better results:
>
> http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows
>
>
> --
> Best Regards,
> David Hutto
> CEO: http://www.hitwebdevelopment.com
>

The problem is related to Python on Mac, not on Windows. As was stated
in the original post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a python license problem?

2012-09-10 Thread Benjamin Kaplan
On Mon, Sep 10, 2012 at 7:58 PM, Jayden  wrote:
> Python is under GPL compatible. If I develop a python code, convert it to 
> executable and distribute the executable as a commercial software. May I need 
> to make my source code open?
>
> If python is under GPL, is the answer different? Thanks a lot!!
> --
> http://mail.python.org/mailman/listinfo/python-list

"GPL compatible" is not a license. It's a quality of the license.
Python's license is compatible with the GPL, which means that you can
use Python in software licensed under the GPL

Python's license (which is available at
http://docs.python.org/license.html ) does not require Python code to
be open source, nor does it prohibit commercial use.

And even if Python was under the GPL, you would still be able to
release your own programs without opening the source. You just
wouldn't be able to modify Python without releasing your changes.
That's how the userland in Mac OS X is still closed-source despite
being compiled with GCC.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess call is not waiting.

2012-09-19 Thread Benjamin Kaplan
On Sep 19, 2012 9:37 AM, "andrea crotti"  wrote:
> Well there is a process which has to do two things, monitor
> periodically some external conditions (filesystem / db), and launch a
> process that can take very long time.
>
> So I can't put a wait anywhere, or I'll stop everything else.  But at
> the same time I need to know when the process is finished, which I
> could do but without a wait might get hacky.
>
> So I'm quite sure I just need to run the subprocess in a subthread
> unless I'm missing something obvious.

If you want to see if a processes has terminated without waiting, use poll.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Pip onto a mac os x system

2012-09-19 Thread Benjamin Kaplan
On Sep 19, 2012 6:37 PM, "John Mordecai Dildy"  wrote:
>
> Does anyone know how to install Pip onto a mac os x ver 10.7.4?
>
> Ive tried easy_instal pip but it brings up this message (but it doesn't
help with my problem):
>
> error: can't create or remove files in install directory
>
> The following error occurred while trying to add or remove files in the
> installation directory:
>
> [Errno 13] Permission denied:
'/Library/Python/2.7/site-packages/test-easy-install-1820.write-test'
>
> The installation directory you specified (via --install-dir, --prefix, or
> the distutils default setting) was:
>
> /Library/Python/2.7/site-packages/
>
> Perhaps your account does not have write access to this directory?  If the
> installation directory is a system-owned directory, you may need to sign
in
> as the administrator or "root" account.  If you do not have administrative
> access to this machine, you may wish to choose a different installation
> directory, preferably one that is listed in your PYTHONPATH environment
> variable.
>
> For information on other options, you may wish to consult the
> documentation at:
>
>   http://peak.telecommunity.com/EasyInstall.html
>
> Please make the appropriate changes for your system and try again.
>
> Thing is I am the Administrator of the computer and can use all of the
folders on the mac computer.
>

No you can't. You can ask permission to use skill the folders (and then
grant yourself that permission), but the user that you're currently running
as does not have full access to the computer.

You know how every time you install a program, a prompt comes up asking for
your password? That's you giving the process permission to run as "root",
the only account with full access to everything.

On the command line, you run things as root by using the "sudo" command
(being an administrator means your account is able to run that)

sudo easy_install pip

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


Re: Can't import modules

2012-09-30 Thread Benjamin Kaplan
On Sun, Sep 30, 2012 at 12:42 PM, Peter Farrell
 wrote:
> Hello!
>
> I'm still new to Python, so here's another easy one. After I save something 
> I've done as a .py file, how do I import it into something else I work on? 
> Every time I try to import something other than turtle or math, I get this 
> error message:
>
> 'module' object is not callable
>
> What am I doing wrong?
>
> Thanks!
>
> Peter Farrell
> San Mateo, CA
> --

Well, you haven't told us what you're doing, so it's hard to say what
you're doing wrong. So I'm going to make a few guesses.

1. Your first (and possibly only other) language was Java.
2. You're making a class (let's say Foo) and putting it in a file of
the same name (Foo.py)
3. You're doing "import Foo" and then calling "Foo()" trying to
instantiate the class.

Python doesn't have that "one class per file, and the file must have
the same name as the class" rule as Java. The file defines a module,
which is an object and can have any number of objects (including
classes, because those are objects too) in it.

$ cat foo.py
class Foo(object):
pass

def add2(y) :
return y + 2
bkaplan:~ bkaplan$ python
Python 2.7.3 (default, Apr 23 2012, 10:06:17)
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> dir(foo)
['Foo', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', 'add2', 'x']
>>> foo()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable
>>> foo.Foo()

>>> foo.add2(5)
7
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't run any script without it failing due to calling tkinter for no reason

2012-10-14 Thread Benjamin Kaplan
On Sun, Oct 14, 2012 at 6:47 PM,   wrote:
> Hello All,
>
>
> I'm running python 3.2 on Freebsd 9.0 Release and I must've screwed up my 
> environment somehow, because now I can't run any script without it failing 
> and throwing:
> ** IDLE can't import Tkinter.  Your Python may not be configured for Tk. **
>
> Yet none of my scripts use tkinter nor call that module. They're simple 
> network scraping scripts. I use pydev and eclipse and must've fat fingered 
> something that screwed up my python environment, but I haven't the slightest 
> clue on how to fix it. I can run my scripts in idle no problem, but I've 
> built them as command line apps. I've tried uninstalling python 3 and 
> reinstalling it to no avail. What did I do, and how can I fix it?
>
> Thanks,
> Adam
> --

IDLE uses Tkinter. If you don't have Tk installed, just run the
scripts from the terminal or pick a different IDE.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nice solution wanted: Hide internal interfaces

2012-10-29 Thread Benjamin Kaplan
On Mon, Oct 29, 2012 at 9:33 AM, Johannes Bauer  wrote:
> Hi there,
>
> I'm currently looking for a good solution to the following problem: I
> have two classes A and B, which interact with each other and which
> interact with the user. Instances of B are always created by A.
>
> Now I want A to call some private methods of B and vice versa (i.e. what
> C++ "friends" are), but I want to make it hard for the user to call
> these private methods.
>
> Currently my ugly approach is this: I delare the internal methods
> private (hide from user). Then I have a function which gives me a
> dictionary of callbacks to the private functions of the other objects.
> This is in my opinion pretty ugly (but it works and does what I want).
>
> I'm pretty damn sure there's a nicer (prettier) solution out there, but
> I can't currently think of it. Do you have any hints?
>
> Best regards,
> Joe
>

What do you mean "declare the internal methods private"? Python
doesn't have this notion of restricted access. By convention, names
starting with a leading underscore are private, but it's not enforced
by the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numpy module

2012-10-29 Thread Benjamin Kaplan
On Sun, Oct 28, 2012 at 10:40 PM,   wrote:
> Hello to the group!
>
> I've learned a lot about Ubuntu just trying to install numpy for Python 
> 3.2.3. I've finally managed to put it in the Python3.2 directory but when I 
> try to import it, I still get there's "no module named numpy." There are 
> other modules in the same directory, like 'email' and it imports fine.
>
> Does Numpy 1.6.2 not run with Python 3.2.3?
>
> Can anybody help? Thank you in advance.
>
> Peter Farrell
> --

Numpy is written in C. You can't just drop the source code into a
folder. It has to be compiled against that version of Python. You
could do that yourself, or you could just run "sudo apt-get install
python3-numpy"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Robust regex

2012-11-19 Thread Benjamin Kaplan
On Nov 19, 2012 12:37 PM, "Joseph L. Casale" 
wrote:
>
> Trying to robustly parse a string that will have key/value pairs separated
> by three pipes, where each additional key/value (if more than one exists)
> will be delineated by four more pipes.
>
> string = 'key_1|||value_1key_2|||value_2'
> regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?'
>
> I am not convinced this is the most effective or safest, any opinions
would
> be greatly appreciated!
>
> jlc
> --
> http://mail.python.org/mailman/listinfo/python-list

Do you even need a regular expression for this? Just split on  and then
split those on |||.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import module whose filename starts number

2012-12-12 Thread Benjamin Kaplan
On Dec 12, 2012 9:47 AM, "Yong Hu"  wrote:
>
> I have a few scripts whose file names start with numbers. For example,
01_step1.py, 02_step2.py
>
> I tried to import them in another script by "import 01_step1" or "from
01_step1 import *". Both failed, saying "SyntaxError: invalid syntax"
>
> Is there anyway to import those files? The file name must start with
characters?
> --

I believe the restriction is that the module names must be valid
identifiers. You may still be able to import them using __import__ and then
assign the resulting module object to a valid name.
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re:

2012-12-15 Thread Benjamin Kaplan
On Sat, Dec 15, 2012 at 5:49 PM, Dustin Guerri  wrote:
>
> Hi there,
>
> I'm new to Python and to programming.  is this the right place for me to
> post a beginner question on Python use ?
>
> Many thanks.
>

You could post questions here, but it would be better to use the
Python-tutor list for that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode

2012-12-17 Thread Benjamin Kaplan
On Mon, Dec 17, 2012 at 12:59 AM, Anatoli Hristov  wrote:
>> What happens when you do use UTF-8?
> This is the result when I encode the string:
> " étroits, en utilisant un portable extrêmement puissant—le plus
> petit et le plus léger des HP EliteBook pleine puissance—avec un
> écran de diagonale 31,75 cm (12,5 pouces), idéal pour le
> professionnel ultra-mobile.
> "
> No accents
>>
>> What do you mean, "use UTF-8"?
>
> Trying to encode the string
>>

What's your terminal's encoding? That looks like you have a CP-1252
terminal trying to output UTF-8 text.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compile python 3.3 with bz2 support

2012-12-22 Thread Benjamin Kaplan
On Dec 21, 2012 1:31 AM, "Isml" <76069...@qq.com> wrote:
>
> hi, everyone:
> I want to compile python 3.3 with bz2 support on RedHat 5.5 but fail
to do that. Here is how I do it:
> 1. download bzip2 and compile it(make、make -f Makefile_libbz2_so、make
install)
> 2.chang to python 3.3 source directory : ./configure
--with-bz2=/usr/local/include
> 3. make
> 4. make install
>
> after installation complete, I test it:
> [root@localhost Python-3.3.0]# python3 -c "import bz2"
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/local/lib/python3.3/bz2.py", line 21, in 
> from _bz2 import BZ2Compressor, BZ2Decompressor
> ImportError: No module named '_bz2'
> By the way, RedHat 5.5 has a built-in python 2.4.3. Would it be a problem?
>
>
> --

What is the output of configure? The last thing it does is list which
modules are not going to be built. Is bz2 on the list? What does configure
say when it's looking for bz2?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-26 Thread Benjamin Kaplan
On Dec 26, 2012 11:00 AM, "Antoon Pardon" 
wrote:
>
> I am converting some programs to python 3. These programs manipulate
tarfiles. In order for the python3 programs to be really useful
> they need to be able to process the tarfiles produced by python2 that
however seems to be a problem.
>
> This is testcode that produces a tarfile.
>
> #! /usr/bin/python
>
> compression = "bz2"
> tarmode = "w|%s" % compression
> rt = '.'
>
> import os
> import os.path
> import errno
>
> import tarfile as tar
>
> def process():
> pj = os.path.join
> entries = os.listdir(rt)
> of = open("DUMP.tbz", "w")
> tf = tar.open(mode = tarmode, fileobj = of,
>   encoding = 'ascii', format = tar.PAX_FORMAT)
> for entry in entries:
> fqpn = pj(rt, entry)
> try:
> tf.add(fqpn, entry, recursive = False)
> except OSError as ErrInfo:
> print("%s: disappeared" % fqpn)
> if ErrInfo.errno != errno.ENOENT:
> raise
> tf.close()
> of.close()
>
> if __name__ == "__main__":
> process()
>
>
==
> This is testcode that checks a tarfile
>
> #!/usr/bin/python
>
> compression = "bz2"
> tarmode = "r|%s" % compression
>
> import os
> import os.path
> import stat
>
> import tarfile as tar
>
> def equalfile(fl1, fl2):
> bf1 = fl1.read(8192)
> bf2 = fl2.read(8192)
> while bf1 == bf2:
> if bf1 == "":
> return True
> bf1 = fl1.read(8192)
> bf2 = fl2.read(8192)
> return False
>
> def process():
> gf = open("DUMP.tbz", "r")
> tf = tar.open(mode = tarmode, fileobj = gf,
>   encoding = 'ascii', format = tar.PAX_FORMAT)
> for tarinfo in tf:
> entry = tarinfo.name
> fileinfo = os.stat(entry)
> if stat.S_ISREG(fileinfo.st_mode) and tarinfo.isreg():
> bfl = tf.extractfile(tarinfo)
> ofl = open(entry)
> if not equalfile(bfl, ofl):
> print("%s: does not match backup" % entry)
> sync = False
> tf.close()
> gf.close()
>
> if __name__ == "__main__":
> process()
>
>
=
>
> When I use python2.7 to produce and later check the tarfile everything
works as expected. However when I use python3.2 to check the tarfile I
> get the following traceback.
>
> Traceback (most recent call last):
>   File "tarchck", line 39, in 
> process()
>   File "tarchck", line 25, in process
> encoding = 'ascii', format = tar.PAX_FORMAT)
>   File "/usr/lib/python3.2/tarfile.py", line 1771, in open
> t = cls(name, filemode, stream, **kwargs)
>   File "/usr/lib/python3.2/tarfile.py", line 1667, in __init__
> self.firstmember = self.next()
>   File "/usr/lib/python3.2/tarfile.py", line 2418, in next
> tarinfo = self.tarinfo.fromtarfile(self)
>   File "/usr/lib/python3.2/tarfile.py", line 1281, in fromtarfile
> buf = tarfile.fileobj.read(BLOCKSIZE)
>   File "/usr/lib/python3.2/tarfile.py", line 573, in read
> buf = self._read(size)
>   File "/usr/lib/python3.2/tarfile.py", line 585, in _read
> buf = self.__read(self.bufsize)
>   File "/usr/lib/python3.2/tarfile.py", line 604, in __read
> buf = self.fileobj.read(self.bufsize)
>   File "/usr/lib/python3.2/codecs.py", line 300, in decode
> (result, consumed) = self._buffer_decode(data, self.errors, final)
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position 10:
invalid start byte
>
> I have been looking around but have no idea how I have to adapt this code
in order to have it process the tarfile under python3.2. The original code
didn't have the coding and format keywords on the tar.open statement and
after reading the documentation I thought that
> would make things work, but no such luck. Further reading didn't
> provide anything usefull
>
> --
> Antoon Pardon
> --

You're opening the file in text mode, so it's trying to decode it as text
using your default encoding (utf-8). You want the file read as a series of
bytes, so open it in binary mode.

gf =open("DUMP.tbz", "rb")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you call a function several times in this context??

2013-01-06 Thread Benjamin Kaplan
On Jan 6, 2013 12:33 PM, "kofi"  wrote:
>
> Using python 3.1, I have written a function called "isEvenDigit"
>
> Below is the code for the "isEvenDigit" function:
>
> def isEvenDigit():
> ste=input("Please input a single character string: ")
> li=["0","2","4", "6", "8"]
> if ste in li:
> print("True")
> else:
> print("False")
>
> I am now trying to write a function that takes a string as an argument
and makes several calls to the isEvenDigit function in order to calculate
and return the number of even digits in the string.How do i do this please?
This is what i have done so far.
>
> def isEvenDigit2():
> number = input("Enter a digit: ")

Use a loop and call the function in the body of the loop. In this case, you
would use a for loop iterating over number. If you don't know how to use a
for loop, I recommend you do the tutorial at
http://docs.python.org/3.3/tutorial/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wiki.python.org

2013-01-09 Thread Benjamin Kaplan
On Wed, Jan 9, 2013 at 8:30 AM, Ken  wrote:
> On Wed, Jan 09, 2013 at 04:05:31PM +, Reed, Kevin wrote:
>> Hello,
>>
>> I have been unable to access wiki.python.org for two days.  Is there a 
>> problem with the server, or is it me?
>>
>> Thank you much,
>>
>> Kevin C. Reed
>> New Python User
>
> Well, I just tried it twice and could not get there, so I would say it
> is a problem on the server's end.
>
> Ken
>
>

The server was compromised with a zero-day remote code exploit. It was
taken offline to prevent further damage.

http://mail.python.org/pipermail/python-list/2013-January/638182.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cymbalic reference?

2013-01-15 Thread Benjamin Kaplan
On Tue, Jan 15, 2013 at 8:56 PM, rh  wrote:
> I have this working and I am curious to know how others do same.
>
> class Abc(object):
> def __init__(self):
> pass
> def good(self):
> print "Abc good"
> def better(self):
> print "Abc better"
>
> urls = {'Abc':'http://example.com'}
> strings = ['good', 'better']
>
> for s in urls:
> o = eval("%s()" % s)
> for string in strings:
> eval("o.%s()" % string)
>
>
> Yes, 'spose symbolic references is what these are
>
> While I'm at it what magic could I use to print "the-class-I-am-in good"
> instead of hard-coding "Abc good"? I tried __class_ and self.__class__
>
> --

Rather than using eval, you can grab the class out of globals(), and
then use getattr to get the methods.

>>> for s in urls :
... o = globals()[s]()
... for method in strings :
... getattr(o, method)()
...
Abc good
Abc better

And for getting the class name, the class has a __name__ attribute. So
you could use self.__class__.__name__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using an object inside a class

2012-01-23 Thread Benjamin Kaplan
On Mon, Jan 23, 2012 at 4:22 PM, Jonno  wrote:
>
>
> On Mon, Jan 23, 2012 at 2:25 PM, Terry Reedy  wrote:
>>
>> On 1/23/2012 2:44 PM, Jonno wrote:
>>>
>>> I have a pretty complicated bit of code that I'm trying to convert to
>>> more clean OOP.
>>>
>>> Without getting too heavy into the details I have an object which I am
>>> trying to make available inside another class. The reference to the
>>> object is rather long and convoluted but what I find is that within my
>>> class definition this works:
>>>
>>> class Class1:
>>>     def __init__(self):
>>>
>>>     def method1(self):
>>>          foo.bar.object
>>>
>>> But this tells me "global name foo is not defined":
>>>
>>> class Class1:
>>>      def __init__(self):
>>>            foo.bar.object
>>>
>>> Obviously I want the object to be available throughout the class (I left
>>> out the self.object = etc for simplicity).
>>
>>
>> Perhaps you left out some relevant details.
>>
> I'm sure I did. Part of the reason I'm not posting the whole code is that
> I'm trying to teach myself OOP as part of this process. I want to figure out
> what is wrong as much as possible by myself. I really appreciate the
> pointers and suggestions though.
>
>>
>>
>>> Any ideas why I can reference foo inside the method but not in __init__?
>>
>>
>> References inside functions are resolved when the function is called. So
>> purely from what you have presented above, it would seem that 'foo' is
>> defined between the call to __init__ and a later call to method1.
>
>
> I have a strong suspicion that this is what's happening.
>
> Method1 is called on a button push when MainLoop is running so obviously foo
> (the main wx.App) exists by then.
> I must have somehow be initializing Class1 before foo = MyApp() happens.
> Is there a good reference on the order that things happen in python when a
> single script is run?
>

"foo = MyApp()" creates an instance of MyApp, initializes it, and then
binds it to the name foo. If Class1 is being initialized in
MyApp.__init__, then the MyApp instance hasn't finished being created
yet so the name "foo" doesn't exist.


> In the meantime here is my stripped down script (foo = app, bar = frame,
> object = graph_panel). I'd welcome all suggestions to reorganize it.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [semi OT]: Smartphones and Python?

2012-02-16 Thread Benjamin Kaplan
On Feb 16, 2012 10:25 AM, "Michael Torrie"  wrote:
>
> On 02/16/2012 07:53 AM, 8 Dihedral wrote:
> > The law suites of JAVA Vitrtual Machine from Oracle
> > are famous now. But in 201X the JVM patents will be
> > expired, thus it is not very urgent to chunk out a new jython now.
Anyway just write codes that can be maintained and  ported to other
languages and platforms
> > easily.
>
> Umm what does this have to do with anything?
>
> You claimed Jython is or will be available on Android. It's not and
> Jython isn't being ported to Dalvik and it has nothing to do with
> patents.  Android might use java a language, but the virtual machines
> are very different.  And no expired patents are going to change that
> fact.  Android simply isn't going to run the JVM anytime soon.
> --

I believe the general consensus is that 8 is a bot. it makes lots of
posts that mention key words from the thread its replying to but don't
actually mean anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python math is off by .000000000000045

2012-02-22 Thread Benjamin Kaplan
On Feb 22, 2012 1:16 PM, "Alec Taylor"  wrote:
>
> Simple mathematical problem, + and - only:
>
> >>> 1800.00-1041.00-555.74+530.74-794.95
> -60.9500045
>
> That's wrong.
>
> Proof
>
http://www.wolframalpha.com/input/?i=1800.00-1041.00-555.74%2B530.74-794.95
> -60.95 aka (-(1219/20))
>
> Is there a reason Python math is only approximated? - Or is this a bug?
>
> Thanks for all info,
>
> Alec Taylor
> --

You aren't doing math with  decimal numbers. you're using IEEE
754-compliant double precision floating point numbers. this isn't just a
python thing. You'd get the same results in C, Java, VB, and pretty much
every other general purpose language written in the last 40 years.

Floats are represented in a form similar to scientific notation (a * 2^b),
so just like scientific notation, there's a finite number of significant
figures. And just like there are rational numbers that can't be represented
in decimal, like 1/3, there are numbers that can't be represented in
binary, like 1/10.

Double-precision numbers are accurate to about 15 decimal digits. if you
need more precision, there is the decimal module but it's way slower
because your processor doesn't natively support it.

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


Re: How can I make an instance of a class act like a dictionary?

2012-02-27 Thread Benjamin Kaplan
On Mon, Feb 27, 2012 at 3:09 PM, John Salerno  wrote:
> On Feb 27, 1:39 am, Chris Rebert  wrote:
>> On Sun, Feb 26, 2012 at 11:24 PM, John Salerno  wrote:
>> > Hi everyone. I created a custom class and had it inherit from the
>> > "dict" class, and then I have an __init__ method like this:
>>
>> > def __init__(self):
>> >        self = create()
>>
>> > The create function creates and returns a dictionary object. Needless
>> > to say, this is not working. When I create an instance of the above
>> > class, it is simply an empty dictionary rather than the populated
>> > dictionary being created by the create function. Am I doing the
>> > inheritance wrong, or am I getting the above syntax wrong by assigning
>> > the return value to self?
>>
>> Assignment to `self` has no effect outside the method in question;
>> Python uses call-by-object (http://effbot.org/zone/call-by-object.htm
>> ) for argument passing.
>> Even in something like C++, I believe assignment to `this` doesn't work.
>>
>> > I know I could do self.variable = create() and that works fine, but I
>> > thought it would be better (and cleaner) simply to use the instance
>> > itself as the dictionary, rather than have to go through an instance
>> > variable.
>>
>> Call the superclass (i.e. dict's) initializer (which you ought to be
>> doing anyway):
>>     super(YourClass, self).__init__(create())
>>
>> Cheers,
>> Chris
>> --http://rebertia.com
>
> Thanks. This ended up working:
>
> def __init__(self):
>        self = super().__init__(create_board())
>
> Is that what you meant for me to do? Why did assigning to self work in
> this case, but not the original case?


It didn't do anything and still isn't doing anything.

In Python, names are assigned to objects


self -> 
  ^
foo ---|

Reassigning a name does not change the value, so
self = create()

Just makes an object2

self -> 

foo ---> 

The reason it's working here is because the super().__init__() call
modifies the existing object in place. It returns None, so you're
setting self = None but that doesn't matter because of what I
explained before about how assigning to self doesn't actually change
anything.
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to write this regular expression?

2012-03-07 Thread Benjamin Kaplan
On Wed, Mar 7, 2012 at 4:11 PM, John Salerno  wrote:
>
> On Wed, Mar 7, 2012 at 3:01 PM, Ian Kelly  wrote:
>
> > There is a fork of setuptools called "distribute" that supports Python
> > 3.
>
> Thanks, I guess I'll give this a try tonight!
>
> > setup.py is a file that should be included at the top-level of the
> > .tar files you downloaded.  Generally, to install something in that
> > manner, you would navigate to that top-level folder and run "python
> > setup.py install".  If you have multiple Python versions installed and
> > want to install the package for a specific version, then you would use
> > that version of Python to run the setup.py file.
>
> The only files included in the .tar.gz file is a .tar file of the same
> name. So I guess the setup option doesn't exist for these particular
> packages. I'll try "distribute" tonight when I have some time to mess
> with all of this.
>
> So much work just to get a 3rd party module installed!
> --


It's because your extraction program is weird. Gzip is a compression
algorithm that operates on a single file. Tar is an archive format
that combines multiple files into a single file. When we say "extract
the .tar.gz", what we mean is both uncompress the tar file and then
extract everything out of that. A lot of programs will do that in one
step. If you look inside the tar file, you should find the setup.py.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python Apps on Mac Lion

2012-03-13 Thread Benjamin Kaplan
On Tue, Mar 13, 2012 at 12:42 PM,  wrote:
>
> Sábado, 25 de Junho de 2011 02h20min49s UTC+1, JKPeck escreveu:
> > The Lion version of the OS on the Mac comes with Python 2.7 installed,
> > but it is in /System/Library/Frameworks/..., and this area is not writable
> > by third party apps.
> >
> > So is there a consensus on what apps that typically install under the
> > Python site-packages directory should do in this situation?  Installing
> > Python from python.org puts it in the writable area
> > /Library/Frameworks/Python.framework.
> >
> > So, what should a Python app installer do?
> >
> > Thanks
>
> Hello,
>
> currently I have:
>
> /Library/Python/2.7/
> /Library/Frameworks/Python.framework/Versions/2.7/
> /Users/user/Library/Python/2.7/
>
> With 3 folders "site-packages" and do not know why.
> What's the difference?
>
> Thanks.
>

If I had to take a guess, having not played too much with Lion:

/Library/Python/2.7 is for user-installed packages for the system
python that are installed for all users.
/Library/Frameworks/... is for the user-installed Python (that's where
it's always gone)
/Users/user/Library... is for user-installed packages for the system
Python that are only installed for the specific user.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run once while loop

2012-04-04 Thread Benjamin Kaplan
On Wed, Apr 4, 2012 at 9:21 AM, Anatoli Hristov  wrote:
> I thing the best will be if I use hundreds of the seconds to print the
> message.
>
> for example at 12:00:00:10, but unfortunately I cant see that I can use
> hundreds of the seconds.
>
> Does anyone knows if I can use it ?
>
> Thanks
>
> Anatoli
>
>

Your proposed solution is one of those hacks that will cause your
program to fail if we get better machines that could run that loop
twice in 1/100th of a second. "When the only tool you have is a
hammer, every problem looks like a nail". You need to add more tools
to your toolbox than an infinite loop. If your problem is that you
want to trigger an event at a specific time, John's answer is the
correct one. If your entire program is just this recurring task, use
your OS's task scheduler (Task Scheduler for Windows, Launchd for Mac
OS X, and Cron for other *nixes).

> On Wed, Apr 4, 2012 at 2:25 PM, John O'Hagan 
> wrote:
>>
>> On Tue, 3 Apr 2012 23:00:22 +0200
>> Anatoli Hristov  wrote:
>>
>> > On 03 Apr 2012, at 22:45, Ian Kelly  wrote:
>> >
>> > > On Tue, Apr 3, 2012 at 2:36 PM, Anatoli Hristov 
>> > > wrote:
>> > >> Hi,
>> > >>
>> > >> I'm trying to do a while loop with condition of time if time is
>> > >> 12:00:00 print text, but for this one second the text is printed at
>> > >> least 50 times, how can I print only once?
>> > >
>> > > Set a flag when you print the text to indicate that you've already
>> > > printed it, and don't print it again if the flag is set.  When it's no
>> > > longer 12:00:00, reset the flag.
>> > >
>> > > That said, a busy while loop is probably the wrong way to do this,
>> > > because it will run your CPU at 100%.  Better would be to put the
>> > > thread to sleep with time.sleep() calls or a real event loop with a
>> > > timer event.
>> > >
>> > > Cheers,
>> > > Ian
>> >
>> > Thank you Ian,
>> >
>> > what if I wait for other conditions if I use time.sleep for 1 sec? it
>> > means that all the program is sleeping for a sec.
>> >
>>
>> If I understand correctly, you don't want the whole program to sleep. If
>> that's the case, you could use threading.Timer, for example:
>>
>> import threading, time
>>
>> def twelve():
>>    print("It's twelve o'clock")
>>
>> local_secs = (time.time() - time.timezone) % (24 * 60 * 60)
>> secs_till_12 = 12 * 60 * 60 - (local_secs % (12 * 60 * 60))
>>
>> wait_till_12 = threading.Timer(secs_till_12, twelve)
>> wait_till_12.start()
>>
>>
>> Regards,
>>
>> John
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Python 3 shell restarting

2012-04-10 Thread Benjamin Kaplan
On Tue, Apr 10, 2012 at 2:36 PM, Franck Ditter  wrote:
> In article
> <19745339.1683.1333981625966.JavaMail.geo-discussion-forums@yncc41>,
>  Miki Tebeka  wrote:
>
>> > How may I get a fresh Python shell with Idle 3.2 ?
>> Open the configuration panel (Options -> Configure IDLE).
>> Look in the "Keys" tab for the shortcut to "restart-shell"
>
> Fine, thanks, but WHY isn't it in a menu (e.g. Debug) ?
> Moreover, I see :
>
>    restart-shell - 
>
> Hum, but when I press, Ctl-F6, nothing happens !!??!! F6 gives me char.
> (MacOS-X Lion, France, Idle 3.3.0a2)
>
> I tried to replace "restart-shell " with F6 (which does nothing except 
> displaying a
> strange character inside a square), but that was refused "already in use"...
>
>    franck
>
> P.S. There is no "configuration panel (Options -> Configure IDLE)",
> only a Preferences menu with a "Key" tab on MacOS-X. May I suggest to the
> Python Idle 3 team to test their software on a Mac ? Please :-)


IDLE is tested on the Mac. But Mac OS X has very different design
guidelines from programs on other systems. The Preferences menu is
pretty much required to be under the Program Name menu, for example.
And all the keyboard shortcuts that use Ctrl on Windows and Linux use
Command on Mac OS X. If you don't specify Mac, we're going to give you
the options that work on Windows and Linux.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trac.util

2012-04-11 Thread Benjamin Kaplan
On Wed, Apr 11, 2012 at 4:52 PM, cerr  wrote:
>
> Hi,
>
> I want to install some python driver on my system that requires trac.util
> (from Image.py) but I can't find that anywhere, any suggestions, anyone?
>
> Thank you very much, any help is appreciated!
>
> Error:
> File "/root/weewx/bin/Image.py", line 32, in 
>    from  trac.util import escape
> ImportError: No module named trac.util
>
>
> Ron
> --

Trac is a project management program. I'm not sure why anything other
than a Trac plugin would have it as a dependency, but there is a
trac.util.escape defined in there.


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


Re: system call that is killed after n seconds if not finished

2012-04-16 Thread Benjamin Kaplan
On Mon, Apr 16, 2012 at 10:51 AM, Jaroslav Dobrek
 wrote:
>
> Hello,
>
> I would like to execute shell commands, but only if their execution
> time is not longer than n seconds. Like so:
>
> monitor(os.system("do_something"), 5)
>
> I.e. the command do_somthing should be executed by the operating
> system. If the call has not finished after 5 seconds, the process
> should be killed.
>
> How could this be done?
>
> Jaroslav

* Use subprocess instead of os.system. subprocess doesn't block
* run the process in another thread and have that thread do nothing
until the process is finished or a terminate flag gets set. If the
flag gets set, call terminate() on the Popen object.
* have the main thread call thread.join(5) on your new thread. After
that, set the terminate flag.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Benjamin Kaplan
On Mon, Apr 23, 2012 at 1:01 PM, Paul Rubin  wrote:
>
> Kiuhnm  writes:
> > I can't think of a single case where 'is' is ill-defined.
>
> If I can't predict the output of
>
>    print (20+30 is 30+20)  # check whether addition is commutative
>    print (20*30 is 30*20)  # check whether multiplication is commutative
>
> by just reading the language definition and the code, I'd have to say
> "is" is ill-defined.
>

The "is" operator is perfectly defined. But it doesn't check to see
whether two objects hold equivalent values, it checks whether they are
the same thing. You're not interested in whether 20+30 and 30+20 are
the same object, you're interested in whether they return equivalent
values which should be checked with ==.

> > You're blaming 'is' for revealing what's really going on. 'is' is
> > /not/ implementation-dependent. It's /what's going on/ that's
> > implementation-dependent.
> > "a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
> > lie to the user?
>
> Whether a and b are the same object is implementation-dependent.
> --

And if I try running "from java.util import ArrayList" in CPython it
will give me an import error. It doesn't mean that the import
mechanism is broken because it returns different results in different
implementations of Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some posts do not show up in Google Groups

2012-04-29 Thread Benjamin Kaplan
On Mon, Apr 30, 2012 at 2:20 AM, Frank Millman  wrote:
>
> Hi all
>
> For a while now I have been using Google Groups to read this group, but on
> the odd occasion when I want to post a message, I use Outlook Express, as I
> know that some people reject all messages from Google Groups due to the high
> spam ratio (which seems to have improved recently, BTW).
>
> >From time to time I see a thread where the original post is missing, but
> the follow-ups do appear. My own posts have shown up with no problem.
>
> Now, in the last month, I have posted two messages using Outlook Express,
> and neither of them have shown up in Google Groups. I can see replies in OE,
> so they are being accepted. I send to the group gmane.comp.python.general.
>
> Does anyone know a reason for this, or have a solution?
>
> Frank Millman

I believe the mail-to-news gateway has trouble with HTML messages. Try
sending everything as plain text and see if that works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: %d not working in re at Python 2.7?

2012-05-14 Thread Benjamin Kaplan
On May 14, 2012 7:06 PM, "vacu"  wrote:
>
> I am frustrated to see %d not working in my Python 2.7 re.search, like
> this example:
>
> >>> (re.search('%d', "asdfdsf78asdfdf")).group(0)
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: 'NoneType' object has no attribute 'group'
>
>
> \d works fine:
>
> >>> (re.search('\d+', "asdfdsf78asdfdf")).group(0)
> '78'
>
>
> And google search ignores % in their search, so I failed to find
> answer from Python mailing list or web,
> Do you have any idea what's problem here?
>
> Thanks a head
> Vacu
> --

There's no problem at all. This is re.search, not scanf. They aren't
supposed to behave the same. In fact, the docs specifically describe how to
simulate scanf using re because python doesn't have a scanf function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install python 2.6 on Ubuntu 12.04

2012-05-22 Thread Benjamin Kaplan
On Tue, May 22, 2012 at 8:09 PM, Dan Stromberg  wrote:
>
> If the pythons you require are in synaptic (sudo to root and run synaptic),
> you probably can just use them.
>
> If not, then you, for each release, need to:
> 1) download a tarball using a browser or whatever
> 2) extract the tarball: tar xvfp foo.tar.bz2
> 3) cd into the newly created, top-level directory, and run ./configure
> --prefix /usr/local/cpython-2.6 (or similar)
> 4) Run "make", optionally with parallelism; I often use number_of_cores+1,
> so for a quad core system, I might use "make -j 5".  This speeds up the
> build.
> 5) Run /usr/local/cpython-2.6/bin/python - just to make sure it gives a
> prompt.  control-d to exit.
> 6) Try running your script with one of your new python builds:
> /usr/local/cpython-2.6/bin/python my-script
>
> I've done this for 2.5, 2.6, 2.7, 3.0, 3.1, 3.2 and the 3.3 preview stuff.
> They cooperate with each other well.  Actually, I scripted out the build so
> that I'd get all 7 built automatically with cython and pylint in them.
>
>

Even easier:

./configure
make
sudo make altinstall

If I recall correctly, that will install it in
/usr/local/lib/python2.6 and it will create /usr/local/bin/python2.6
but it will not create /usr/local/bin/python so it won't clobber the
system python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import Webkit and object in Official Python (not MacPorts python) without X11.

2012-05-26 Thread Benjamin Kaplan
On Sat, May 26, 2012 at 9:31 AM, Mr.T Beppu  wrote:
> I think that I will make a browser in Official Python (not MacPorts
> Python).
> What should I do in order to install Webkit for Official Python (not
> MacPorts Python) ?
> from tokyo Japan.
>

You don't just "install WebKit". You need a GUI framework. My
suggestion would be to install PySide, which is a QT wrapper that
includes a Webkit component. The other option is to use PyObjC to
build a Cocoa GUI but then you're restricted to Mac OS X only.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ./configure

2012-06-03 Thread Benjamin Kaplan
>
> Thanks Alain.  I should have a compiler on my Mac OS X Lion.  I am thinking 
> that it isn't set in my $PATH variable.  I don't know where the $PATH is set 
> at.  I will check to see if their is a binary.
> --
> http://mail.python.org/mailman/listinfo/python-list

You need to install the command line tools package within XCode in
order to get them on the path. Or, I guess you could just add XCode's
bin directory to the path. It's usually set in ~/.bash_profile

Or you could just use the binary installer from
http://python.org/download/releases/2.7.3/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Mailman

2012-06-03 Thread Benjamin Kaplan
On Mon, Jun 4, 2012 at 12:49 AM, Chris Rebert  wrote:
> On Sun, Jun 3, 2012 at 9:04 PM, Janet Heath
>  wrote:
>> checking for --with-python... no
>> checking for python... /usr/bin/python
>> checking Python interpreter... /usr/bin/python
>> checking Python version... 2.7.1
>> checking Python's email package... ok
>> checking Japanese codecs... ok
>> checking Korean codecs... ok
>> checking that Python has a working distutils... configure: error:
>>
>> * Distutils is not available or is incomplete for /usr/bin/python
>> * If you installed Python from RPM (or other package manager)
>> * be sure to install the -devel package, or install Python
>> * from source.  See sec. 15.1 of the Installation Manual for
>> * details
>>
>> When I try to check the configuration ./configure for Mailman, I get
>> the above messages.
>
> What *nix flavor or Linux distro are you running?
>
> Cheers,
> Chris

Based on the previous post (./configure), I would assume OS X Lion. I
would also assume she gave up on compiling 2.7.3 herself because it's
only finding the system Python.

Janet, did you install the binary from http://www.python.org? If so,
look up the --with-python argument it's checking for (./configure
--help) and set the Python location accordingly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the latest step by step guide to use Jython to compilePython into Java?

2012-06-04 Thread Benjamin Kaplan
On Mon, Jun 4, 2012 at 11:47 AM, David Shi  wrote:
> Hello, Mohan,
>
> Did you test it?  I am using Windows.  Where are the exact steps for
> compiling in DOS?
>
> Once .class or jar files created, how to use these files?
>
> Could you enlighten me with tested/proven step by step instructions?
>
> Regards.
>
> David
>
> ___

David,

Jythonc has been deprecated for years and hasn't been included with
Jython since 2.2. Nor does it support any language feature newer than
2.2. I don't think anyone managed to get the python to JVM byte code
compiler working either since JVM byte code is notoriously bad for
things that don't behave like Java.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing ints to a function

2012-06-08 Thread Benjamin Kaplan
On Fri, Jun 8, 2012 at 7:41 PM, stayvoid  wrote:
> Hello,
>
> I want to pass several values to a function which is located on a
> server (so I can't change its behavior).
> That function only accepts five values which must be ints.
>
> There are several lists:
> a = [1, 2, 3, 4, 5]
> b = [5, 4, 3, 2, 1]
> c = [0, 0, 0, 0, 0]
>
> I want to pass each value from these lists to that function.
> What is the most pythonic way?
>

function(*a)

* expands a list into positional arguments and ** expands a dictionary
into keyword arguments.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py3.3 unicode literal and input()

2012-06-18 Thread Benjamin Kaplan
On Mon, Jun 18, 2012 at 1:19 AM, jmfauth  wrote:
> What is input() supposed to return?
>
 u'a' == 'a'
> True

 r1 = input(':')
> :a
 r2 = input(':')
> :u'a'
 r1 == r2
> False
 type(r1), len(r1)
> (, 1)
 type(r2), len(r2)
> (, 4)

>
> ---
>
> sys.argv?
>
> jmf

Python 3 made several backwards-incompatible changes over Python 2.
First of all, input() in Python 3 is equivalent to raw_input() in
Python 2. It always returns a string. If you want the equivalent of
Python 2's input(), eval the result. Second, Python 3 is now unicode
by default. The "str" class is a unicode string. There is a separate
bytes class, denoted by b"", for byte strings. The u prefix is only
there to make it easier to port a codebase from Python 2 to Python 3.
It doesn't actually do anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import data from MySQL db into excel sheet

2011-06-06 Thread Benjamin Kaplan
On Mon, Jun 6, 2011 at 9:35 AM, Prasad, Ramit  wrote:
>> Currently i am importing the Database into CSV file using csv module,
>>in csv file i need to change the column width according the size of
>>the data. i need to set different column width for different columns
>>pleas let me know how to achieve this
>
> If you are using xlwt:
> sheet.col(9).width = 3200
>
> I am not sure exactly what unit the 3200 represents so I just adjust this 
> manually to be a size that works for me.
>
>
> Ramit
>
>

xlwt is a package for editing Excel files. CSV, despite being a format
that Excel can open, is not an Excel file. A CSV is to spreadsheets
what plain text is to word processing. It's an extremely simple, easy
to use format programaticfally but it doesn't support any formattting
of any kind.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In Python 2.x, is it possible to make unicode as default like in Python 3.x?

2011-06-08 Thread Benjamin Kaplan
On Wed, Jun 8, 2011 at 11:22 AM, G00gle and Python Lover
 wrote:
> Hello.
> I almost like everything in Python. Code shrinking, logic of processes,
> libraries, code design etc.
> But, we... - everybody knows that Python 2.x has lack of unicode support.
> In Python 3.x, this has been fixed :) And I like 3.x more than 2.x
> But, still major applications haven't been ported to 3.x like Django.
> Is there a way to make 2.x behave like 3.x in unicode support?
> Is it possible to use Unicode instead of Ascii or remove ascii?
> Python with ascii sucks :S
> I know:
>>
>> >>> lackOfUnicodeSupportAnnoys = u'Yeah I finally made it! Should be a
>> >>> magical thing! Unmögötich! İnanılmaz! Süper...'
>>
>> >>> print lackOfUnicodeSupportAnnoys
>>
>> Yeah I finally made it! Should be a magical thing! Unmögötich! Ýnanýlmaz!
>> Süper...
>>
>> >>> # You see the Turkish characters are not fully supported...
>>
>> >>> print str(lackOfUnicodeSupportAnnoys)
>>
>> Traceback (most recent call last):
>>
>> File "", line 1, in 
>>
>> print str(lackOfUnicodeSupportAnnoys)
>>
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in
>> position 54: ordinal not in range(128)
>>
>> >>> # Encode decode really sucks...
>>
>> >>> lackOfUnicodeSupportAnnoys = 'Yeah I finally made it! Should be a
>> >>> magical thing! Unmögötich! İnanılmaz! Süper...'
>>
>> >>> # Look that I didn't use 'u'
>>
>> >>> print lackOfUnicodeSupportAnnoys
>>
>> Yeah I finally made it! Should be a magical thing! Unmögötich! İnanılmaz!
>> Süper...
>>
>> >>> # This time it worked, strange...
>>
>> >>> lackOfUnicodeSupportAnnoys = unicode('Yeah I finally made it! Should
>> >>> be a magical thing! Unmögötich! İnanılmaz! Süper...')
>>
>> Traceback (most recent call last):
>>
>> File "", line 1, in 
>>
>> lackOfUnicodeSupportAnnoys = unicode('Yeah I finally made it! Should be a
>> magical thing! Unmögötich! İnanılmaz! Süper...')
>>
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 54:
>> ordinal not in range(128)
>>
>> >>> # Some annoying error again
>>
>> >>> lackOfUnicodeSupportAnnoys
>>
>> 'Yeah I finally made it! Should be a magical thing! Unm\xf6g\xf6tich!
>> \xddnan\xfdlmaz! S\xfcper...'
>>
>> >>> # And finally, most annoying thing isn't it?
>
> Thanks...

I think you're misunderstanding what Unicode support means. Python 2
does have unicode support, but it doesn't do Unicode by default. And a
lack of Unicode by default does not mean ASCII either.


There are two ways of looking at strings: as a sequence of bytes and
as a sequence of characters. In python 2, a sequence of bytes is
declared by "" and a sequence of characters is declared u"". In Python
3, a sequence of bytes is declared as b"" and a sequence of characters
is declared "".

An encoding is a function that maps bytes to characters. The only time
it matters is when you are trying to convert from bytes to characters.
This is needed because you can't send characters out over a socket or
write them to a file- you can only send bytes.

When you want to convert from bytes to characters or vice versa, you
need to specify an encoding. So instead of doing str(foo), you should
do foo.encode(charset), where charset is the encoding that you need to
use in your output. Python will try to figure out the encoding your
terminal uses if it can, but if it can't, it will fall back to ASCII
(the lowest common denominator) rather than guess. That behavior has
not changed between Python 2 and Python 3 (except that Python is more
aggressive in its attempts to figure out the console encoding).

The reason your first example didn't work is because Python defaulted
to using one encoding to interpret the bytes when you declared the
string as Unicode (perhaps a Western Eurpean encoding) and that
encoding was different than the encoding your terminal uses. In a
Python script, you can fix that by declaring the encoding of the
source file using one of the methods specified in PEP 263 (implemented
in Python 2.3). The second example worked because there was no
conversion- you gave Python a sequence of bytes and it outputted that
sequence of bytes. Since your source and destination have the same
encoding, it happens to work out.


Your last example does show something that has changed as a result of
the Unicode switch. In Python 2, the repr() of a string was
intentionally shown as ASCII with the escape sequences for non-ASCII
characters to help people on terminals that didn't support the full
Unicode character set. Since the default type of string is Unicode in
Python 3, that's been switched to show the characters unless you
explicity encode the string using "string-escape".

The only other major thing that Python 3 added in addition to Unicode
being the default is that you can have non-ASCII variable names in
your source code.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE

2011-06-08 Thread Benjamin Kaplan
On Wed, Jun 8, 2011 at 1:09 PM, Cathy James  wrote:
> I am almost there, but I need a little help:
>
> I would like to
>
> a) print my dogs in the format  index. name: breed as follows:
>
> 0. Mimi:Poodle
> 1.Sunny: Beagle
> 2. Bunny: German Shepard
> I am getting
>
> (0, ('Mimi', 'Poodle')) . Mimi : Poodle instead-what have I done wrong?
>
> b) I would like to append to my list, but my line dogs.dogAppend() is
> giving a TypeError:
>
> for i in enumerate (self.dogAppend()):
> TypeError: 'list' object is not callable
>
> Any help?
>
> #MY CODE BELOW:
>
> import sys
> class Dog():
>    def __init__(self, name, breed):
>        self.name = name
>        self.breed = breed
>
>    def dogAppend(self):
>        self.dogAppend = []
>        self.dogAppend.append((self.name,self.breed))
>        return self.dogAppend
>

In Python, everything is an object. And when we say everything, we
really do mean everything. A function is an object too. So when you do
self.dogAppend = [], you're replacing self.dogAppend (the function
object) with a list.

>
>    def display (self):
>        for i in enumerate (self.dogAppend()):

I don't know what you're trying to do here, because this makes no
sense. dogAppend is going to return a list of a single object, so it's
going to be 0 every time. And enumerate returns two things: the index
and the object. Since you only specified one variable, you get the
tuple of (index, object) which is what you're seeing.

You're supposed to do :

for i, dog in enumerate(a_list_of_all_the_dogs) :
            print (i,".",  dog.name, ": " + dog.breed)

for what you're  trying to get.

>
> if __name__ == "__main__":
>    dogs = Dog(name=input (" Enter Dog Name: "), breed=input ("Enter
> Dog Breed: "))
>    while not dogs:
>        print("Goodbye!!")
>        sys.exit()
>    else:
>        #dogs.dogAppend()
>        dogs.display()
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the stupid encoding problem to stdout

2011-06-08 Thread Benjamin Kaplan
2011/6/8 Sérgio Monteiro Basto :
> hi,
> cat test.py
> #!/usr/bin/env python
> #-*- coding: utf-8 -*-
> u = u'moçambique'
> print u.encode("utf-8")
> print u
>
> chmod +x test.py
> ./test.py
> moçambique
> moçambique
>
> ./test.py > output.txt
> Traceback (most recent call last):
>  File "./test.py", line 5, in 
>    print u
> UnicodeEncodeError: 'ascii' codec can't encode character
> u'\xe7' in position 2: ordinal not in range(128)
>
> in python 2.7
> how I explain to python to send the same thing to stdout and
> the file output.txt ?
>
> Don't seems logic, when send things to a file the beaviour
> change.
>
> Thanks,
> Sérgio M. B.

That's not a terminal vs file thing. It's a "file that declares it's
encoding" vs a "file that doesn't declare it's encoding" thing. Your
terminal declares that it is UTF-8. So when you print a Unicode string
to your terminal, Python knows that it's supposed to turn it into
UTF-8. When you pipe the output to a file, that file doesn't declare
an encoding. So rather than guess which encoding you want, Python
defaults to the lowest common denominator: ASCII. If you want
something to be a particular encoding, you have to encode it yourself.

You have a couple of choices on how to make it work:
1) Play dumb and always encode as UTF-8. This would look really weird
if someone tried running your program in a terminal with a CP-847
encoding (like cmd.exe on at least the US version of Windows), but it
would never crash.
2) Check sys.stdout.encoding. If it's ascii, then encode your unicode
string in the string-escape encoding, which substitutes the escape
sequence in for all non-ASCII characters.
3) Check to see if sys.stdout.isatty() and have different behavior for
terminals vs files. If you're on a terminal that doesn't declare its
encoding, encoding it as UTF-8 probably won't help. If you're writing
to a file, that might be what you want to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 OR 3.2

2011-06-10 Thread Benjamin Kaplan
On Thu, Jun 9, 2011 at 11:00 PM, harrismh777  wrote:
> Andrew Berg wrote:
>>
>> AFAICT, there are three reasons to learn Python 2:
>
>   ... there is a fourth reason.
>
> The linux distro you are using currently was customized with python 2.x
>
> I ran into this problem this week in fact... on my HP g6 ubuntu notebook
> running 10.04 lucid. It ships with the 2.6.5 interpreter. I installed 2.7.1
> and 3.2 (from sources) and was working along happy as a clam until I needed
> to configure a printer... and the config tools would not function... some of
> them would not even open.  Want to guess?  Yup, the config tools are (some
> of them) written in python 2.6-- and they don't run in 2.7.1 nor 3.2  .   :(
>
> So, be careful.  I have had to separate *all* of my python installs on
> *every* one of my systems for this similar reason. The bottom line is if the
> distro ships with 2.6 (minus the idle) chances are that the interpreter is
> there *not* to advocate for python explicitly, but because the interpreter
> is being used by the system somewhere. If you install 2.7 or 3.2 you need to
> be careful to *not* interfere with the default setup.
>
> So, you will need to be able to use both.  There is no getting around it...
> but, I would start with 3.2 (seriously). Get 3.2 under your belt and then
> when you need to, go back and deal with the 2.6 regression.
>
> 3.2 is better built, is more logically consistent (it really is, no
> kidding), and has some new features that make it very attractive. The
> down-side is that some (most) of the library support is still not there for
> many projects.   It will take some time, but it will happen.
>
>

There's an altinstall make target that you're supposed to use in cases
like this. It won't make the /usr/local/bin/python symlink (or
whatever prefix you're using), just pythonx.y. This way, the programs
that depend on "python" referring to a specific version will still
continue to work and you can have your newer version. The Ubuntu
packages that depend on the system Python+ system installed packages
*should* be specifying /usr/bin/python specifically but as you can
see, they don't always do that.

>
> kind regards,
> m harris
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question About Command line arguments

2011-06-10 Thread Benjamin Kaplan
On Jun 10, 2011 10:26 AM, "Mark Phillips" 
wrote:
>
> I have a script that processes command line arguments
>
> def main(argv=None):
> syslog.syslog("Sparkler stared processing")
> if argv is None:
> argv = sys.argv
> if len(argv) != 2:
> syslog.syslog(usage())
> else:
> r = parseMsg(sys.argv[1])
> syslog.syslog(r)
> return 0
>
> if __name__ == "__main__":
> sys.exit(main())
>
> When I run "python myscript fred" it works as expected - the argument fred
is processed in parseMsg as sys.arv[1]
>
> When I run "echo fred | python myscript" the script thinks there are no
arguments, so it prints out the usage statement.
>
> Is the problem with the echo command, or how I wrote my script?
>
> Thanks!
>
> Mark
>

Nothing wrong with either. The problem is a misunderstanding in how the
command line works. When you write "python myscript fred", the shell calls
the python executable and passes the arguments "myscript" and "fred" to the
main function. In the second example, the shell calls "python myscript" and
then sends echo's stdout in to python's stdin. It's not passed as an
argument.

If you were to call raw_input() on the second example, it would return
"fred" without prompting you for anything because raw_input reads from stdin
which in this case is the result of echo.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question About Command line arguments

2011-06-10 Thread Benjamin Kaplan
On Fri, Jun 10, 2011 at 11:31 AM, Tim Chase
 wrote:
> On 06/10/2011 12:58 PM, Mark Phillips wrote:
>>
>> How do I write my script so it picks up argument from the
>> output of commands that pipe input into my script?
>
> You can check
>
>  if os.isatty(sys.stdin):  # <-- this check

Any reason for that over sys.stdin.isatty()?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt

2011-06-10 Thread Benjamin Kaplan
On Fri, Jun 10, 2011 at 12:15 PM, KK  wrote:
> Thanks for the reply!!
> i ve installed the binary
> but when i import anything of PyQt in my prog it says error??
> i think there is some problem with folders


What is the exact text of the error message? We can't help you unless
we know exactly what's wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: debian defaults not up-to-date

2011-06-12 Thread Benjamin Kaplan
On Jun 12, 2011 10:32 AM, "blues2use"  wrote:
>
> Just finished installing Mint 10 and all has gone well. However, when I
> removed some applications, I received this error during the removal:
>
> INFO: using unknown version '/usr/bin/python2.7' (debian_defaults not up-
> to-date?)
>
> The removal proceeds without any other warnings or errors.
>
> Not sure what I should do to correct this.
>
> Your help is most appreciated...
>
> Thanks in advance
> --

This is a Mint question. You'll probably get better answers on their forum.
It has to do with their package manager. Python just happens to be the
package that's messed up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subsetting a dataset

2011-06-12 Thread Benjamin Kaplan
On Sun, Jun 12, 2011 at 9:53 PM, Kumar Mainali  wrote:
> I have a huge dataset containing millions of rows and several dozen columns
> in a tab delimited text file.  I need to extract a small subset of rows and
> only three columns. One of the three columns has two word string with header
> “Scientific Name”. The other two columns carry numbers for Longitude and
> Latitude, as below.
> Sci Name Longitude Latitude Column4
> Gen sp1 82.5 28.4 …
> Gen sp2 45.9 29.7 …
> Gen sp1 57.9 32.9 …
> … … … …
> Of the many species listed under the column “Sci Name”, I am interested in
> only one species which will have multiple records interspersed in the
> millions of rows, and I will probably have to use filename.readline() to
> read the rows one at a time. How would I search for a particular species in
> the dataset and create a new dataset for the species with only the three
> columns?
> Next, I have to create such datasets for hundreds of species. All these
> species are listed in another text file. There must be a way to define an
> iterative function that looks at one species at a time in the list of
> species and creates separate dataset for each species. The huge dataset
> contains more species than those listed in the list of my interest.
> I very much appreciate any help. I am a beginner in Python. So, complete
> code would be more helpful.
> - Kumar

Read in the file with the lists of species. For each line in that
list, open up a file and then put it into a dictionary where the key
is the species name and the value is the file. Then, once you have all
your files created, open up the second file. For each line in the
second file, split it on the tabs and check to see if the first item
is in the dict. If it is, grab your necessary values and write it to
that corresponding file. In rough, untested code

animals = dict()
for line in open('species_list) :
#make a file for that animal and associate it with the name
animals[line.strip()] = open('%s_data.csv' % line.strip(),'w')


#now open the second file
for line in open('animal_data') :
data = line.split('\t')
if data[name_col] in animals :
animals[data[name_col]].write('%s\t%s\t%s' & (data[name_col],
data[lat_col], data[lon_col])

replacing the respective file names and column numbers as appropriate,
of course.

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


Re: Python 2.7.2 for Windows reports version as 2.7.0?

2011-06-17 Thread Benjamin Kaplan
On Fri, Jun 17, 2011 at 5:55 PM,   wrote:
> Just installed the 32-bit version Python 2.7.2 for Windows via the
> python-2.7.2.msi download.
>
> When I start Python via python.exe or Idle, the version info is reported as
> 2.7.0 vs. 2.7.2.
>
> Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on
> win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
 import sys
 sys.version_info
> sys.version_info(major=2, minor=7, micro=0, releaselevel='final', serial=0)

>
> Here's the info on python.exe
>
> 06/12/2011  03:09 PM    26,624 python.exe
> 06/12/2011  03:06 PM    27,136 pythonw.exe
>
> Is this a bug or did I upgrade my version of Python 2.7 wrong?
>
> Thank you,
> Malcolm

The file info is seems correct but I just checked the MSI and it's
reporting that it's 2.7.2. How exactly are you running python.exe and
IDLE- are you calling the full path, just calling "python" and using
whichever python version is first on your path, or are you using an
entry in the start menu? The only thing I can think of is that your
2.7.0 install is in a different location than your 2.7.2 install. So
2.7.2 installed correctly but you're still running the old one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing NLTK

2011-06-17 Thread Benjamin Kaplan
On Fri, Jun 17, 2011 at 1:57 PM, Nige Danton  wrote:
> Hans Mulder  wrote:
>> On 17/06/11 21:58:53, Nige Danton wrote:
>>> Mac OSX python 2.6.1: I'm trying to install the natural language toolkit
>>> and following the instructions here www.NLTK.org/download I've downloaded
>>> the PyYAML package and in a terminal window tried to install it. However
>
>> You're not really giving us enough information, so I'll just guess:
>
> Sorry.
>
>> Are you trying a command that begins with "sudo"?
>
> Good guess. Yes it's sudo python setup.py install
>
>> If so, then you user password should work, provided you're a member
>> of the 'admin' group.  To find out, type "groups" in a Terminal
>> window.  If the response does not include "admin" as a separate
>
> Ok, thanks. Tried that and the response does not include admin nor my user
> name
>
>> word, then you''l have to ask someone to give you admin rights.
>
> It's a personal computer - there is no one to ask.
>
> When I try my user password the reply is that it's not in the sudoers file
> and the admin password it just rejects. Any idea what I should do?
>
> --
> Nige Danton - Replace the obvious with g.m.a.i.l

You need to switch to the admin user. Sudo will only accept your own
password, and only if you're in the "sudoers" file. If you don't want
to log out, you can use the "su admin" command to change to admin
within that shell- that one is expecting your admin password. Then as
the admin, do the sudo python setup.py install and enter your admin
password again.

The point in all this is that your admin isn't actually an admin.
There is only one account on the computer that actually has access to
the core system files and that's "root". "sudo" is a command that lets
you execute a command as another user by entering your own password.
If you don't specify a user, it defaults to using root. An "admin"
account on a Unix system is just an account with permission to use the
sudo command.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is this syntax ?

2011-06-19 Thread Benjamin Kaplan
On Sun, Jun 19, 2011 at 2:06 PM, Vito 'ZeD' De Tullio
 wrote:
> Roy Smith wrote:
>
>> There's something nice about building up strings in-line, as
>> opposed to having to look somewhere to see what's being interpolated.
>> To give a more complex example, consider:
>>
>> print "$scheme://$host:$port/$route#$fragment"
>>
>> That certainly seems easier to me to read than:
>>
>> print "%s://%s:%s/%s#%s" % (scheme,
>>                             port,
>>                             host,
>>                             route,
>>                             fragment)
>>
>> because I don't have to line up the nth format specifier with the nth
>> data item.
>
> well, in python3 you can use dict to format strings
>
 print("%(a)s" % {'a':'b'})
> b
>
> and you can achieve php interpolation via locals()
>
 a = 'b'
 print("%(a)s" % locals())
> b
>
>
> --
> By ZeD

That's a lot older than Python 3. Here's the example from the 2.3
docs:  http://docs.python.org/release/2.3/lib/typesseq-strings.html

Python 3 added a different syntax for string formatting, using .NET's
formatting syntax instead of C's.

"{scheme}://{host}:{port}/{route}#{fragment}".format(locals())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to write this base class?

2011-06-20 Thread Benjamin Kaplan
On Sun, Jun 19, 2011 at 9:04 PM, John Salerno  wrote:
> On Jun 19, 8:52 pm, Chris Kaynor  wrote:
>
>> Having a character class (along with possibly player character, non-player 
>> character, etc), make sense; however you probably want to make stuff like 
>> health, resources, damage, and any other attributes not be handles by any 
>> classes or inheritance in order to allow you to make such data-driven (ie, 
>> read from a file). Doing so makes the game much more extendable: using 
>> classes, you are likely limited to 5 or 'combinations and a few developers 
>> (plus, any designers need to know programming).
>>
>> A basic way to determine between using subclasses over a data driven 
>> approach is: is there significantly different back-end behavior or merely 
>> attribute differences.
>
> Can you give a basic example of how this data-driven approach would
> work? You don't have to provide any code, just a description would be
> helpful. Such as, do I create a data file per character, and then have
> each character instance read/write to that file? Is it good to have so
> many files open at once, or would they only need to be read, closed,
> then opened again at the end to write?
> --

I'm pretty sure he means that if the only difference between classes
is configuration (i.e. you aren't actually going to change code
between character classes, just base stats, growth rates, and a list
of available skills or something of that nature), then you should
store the configurations in a config file rather than making a new
class. So rather than having
class WizardCharacter(Character) :
base_health = 50
...
class WarriorCharacter(Character) :
base_health=70
...
You make a config file

--- characterclasses.ini ---
[Wizard]
base_health=50
[Warrior]
base_health=70

Then, when you make a new character, rather than doing a
WizardCharacter() or a WarriorCharacter(), you do a
Character(job='Wizard') and then look up the various defaults in your
config file. Doing it this way makes it trivial to add a new class. If
you want to use an old-fashioned INI file, you can use the
ConfigParser class to read them. If you want to nest attributes (for
instance, a list of sub-items), you'll probably want to go with XML
and ElementTree. I guess you can also use JSON (which uses a syntax
similar to Python's dictionaries) but I've never really tried to make
one of those by hand before so I'm not sure how well it will work out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do we still need to inherit from "object" to create new-style classes?

2011-06-20 Thread Benjamin Kaplan
On Mon, Jun 20, 2011 at 6:26 PM, John Salerno  wrote:
> I can't quite seem to find the answer to this anywhere. The book I'm
> reading right now was written for Python 3.1 and doesn't use (object),
> so I'm thinking that was just a way to force new-style classes in 2.x
> and is no longer necessary in 3.x. Is that right?
>
> (The documentation doesn't mention object anymore, but elsewhere on
> the Python website it says the documentation hasn't been updated for
> new-style classes yet, hence my confusion.)
>
> Thanks.

3.x got rid of old-style classes altogether, so you are correct-
there's no need to explicitly subclass object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better way to iterate over indices?

2011-06-21 Thread Benjamin Kaplan
On Tue, Jun 21, 2011 at 11:05 AM, Billy Mays  wrote:
> I have always found that iterating over the indices of a list/tuple is not
> very clean:
>
> for i in range(len(myList)):
>    doStuff(i, myList[i])
>
>
>
>
> I know I could use enumerate:
>
> for i, v in enumerate(myList):
>    doStuff(i, myList[i])
>
> ...but that stiff seems clunky.

Why does enumerate seem clunky, other than the fact that you should
probably have
doStuff(i,v)
instead of myList[i] in there? It's a bit more awkward than C's
syntax, but since the typical use case is just iteration anyway, it's
not a huge deal for those few cases where you actually need the
indices.

>
> Are there any better ways to iterate over the indices of a list /tuple?
>
> --Bill
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running an existing script

2011-06-21 Thread Benjamin Kaplan
On Tue, Jun 21, 2011 at 10:45 AM, Adam Chapman
 wrote:
> Hi,
>
> I'm trying to put together a lot of pieces of source code in matlab,
> java, perl and python.
>
> Im an expert when it comes to matlab, but novice in all the others
> listed above. However, I have integrated the java and perl code so
> they can be called from matlab.
>
> I know that there is a toolbox out there called Pymat but i think that
> uses 32bit activex so rules my configuration out.
>
> However I think I can hack in to the python command prompt from
> matlab.
>
> Basically I just want to run a single script from the python command
> window. Once I know how to do that I can be off on my way to perform
> the matlab interfacing.
>
> there is an example of the command I need in the python prompt at
> http://jboost.sourceforge.net/doc.html#cv .
>
> however, I can't seem to run the python script by typing the command
> on that link in the python prompt.
>

That command they show isn't run from a Python shell. It's run from
either a Unix shell (bash and friends) or a Windows command prompt
(cmd). If you want to run a script, you have to give the path to that
script. ./ means the current directory and .. is the parent directory
if you want to give relative paths, or you can just write out the
whole file path.

> Can I please ask how to set the current duirectory in python?
>

os.chdir changes the current directory, but you probably don't need to do that.

> the script I want to run is in a different directory to the one python
> is installed to
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-21 Thread Benjamin Kaplan
On Tue, Jun 21, 2011 at 4:30 PM, Terry Reedy  wrote:
> On 6/21/2011 3:48 PM, John Salerno wrote:
>
>> Absolutely not! Each problem has been designed according to a "one-
>> minute rule", which means that although it may take several hours to
>> design a successful algorithm with more difficult problems, an
>> efficient implementation will allow a solution to be obtained on a
>> modestly powered computer in less than one minute."
>
> That statement is for C, not Python. Python is efficient with human time,
> but not machine time. If something really takes a minute in C, allow
> yourself at least 10 minutes or even more with plain CPython.
>
> --
> Terry Jan Reedy

Python is the second most popular language on Project Euler, at 14358
users compared to 15897 who use C/C++. I'm pretty sure they don't
assume you use C. Although Python's longs do make some of the early
problems really really easy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Security test of embedded Python

2011-06-21 Thread Benjamin Kaplan
On Tue, Jun 21, 2011 at 7:40 PM, Paul Rubin  wrote:
> Chris Angelico  writes:
>> I'll also be looking into Pike. Unfortunately its community is far
>> smaller than Python's, so security holes may be less obvious.
>
> Actually the most obvious and widespread sandboxed language these days
> is Javascript.  There's several embeddable implementations.  Maybe you
> should just use one of those.

Use Pyjamas with that and now you have your sandboxed Python :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writable iterators?

2011-06-22 Thread Benjamin Kaplan
On Jun 22, 2011 12:31 PM, "Neal Becker"  wrote:
>
> AFAICT, the python iterator concept only supports readable iterators, not
write.
> Is this true?
>
> for example:
>
> for e in sequence:
>  do something that reads e
>  e = blah # will do nothing
>
> I believe this is not a limitation on the for loop, but a limitation on
the
> python iterator concept.  Is this correct?

consider the following code

x = [1,2,3]
y = x[0]
y = 5

Would you expect x to be [5,2,3] now? Assignment in python assigns a name to
an object. It doesn't change the value of a variable.

If you have a generator, you can use send() to put data in you need the
actual generator itself to do that.

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


Re: connect windows share

2011-06-22 Thread Benjamin Kaplan
On Jun 22, 2011 11:44 AM, "Travis Altman"  wrote:
>
> I want to be able to connect to a windows share via python.  My end goal
is to be able to recursively search through windows shares.  I want to do
this in Linux as well.  So given a share such as \\computer\test I would
like to search through the test directory and any sub directories for any
file names of interest.  What's the best way of going about this?  I know
LDAP / AD creds may play an essential part in this as well.  Thanks for your
input.
>
> --

I haven't done anything with this myself, but my guess would be that there's
a Python samba wrapper somewhere that you'll want to use for this.

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


Re: python 3 constant

2011-06-22 Thread Benjamin Kaplan
On Jun 22, 2011 12:03 PM, "sidRo"  wrote:
>
> How to declare a constant in python 3?
> --

You don't. Python doesn't have declarations (other than global and
nonlocal). Convention is that anything in all caps  should be considered a
constant but there's no language-level enforcement of it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mac OS X 10.6.6 and MacPyhton 2.6 idle doesn't work

2011-06-23 Thread Benjamin Kaplan
On Jun 23, 2011 10:42 AM, "mando"  wrote:
>
> I've installed MacPython 2.6 under mac os x 2.6 and the IDLE doesn't
> work.
> I post error log. Suggestions?
>
> Thanks a lot.
>
> Luca
>

You'll have to install Tcl yourself. The 2.6 binaries were compiled against
a newer version than Apple ships.

>
> 23/06/11 19.18.01   Apple80211 framework[211]
> ACInterfaceGetPower called
> with NULL interface
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]
> Traceback (most
> recent call last):
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]  File
> "/
> Applications/Python 2.6/IDLE.app/Contents/Resources/idlemain.py",
> line
> 30, in 
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]
> main()
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]  File
> "/
> Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
> idlelib/
> PyShell.py", line 1382, in main
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]
> root =
> Tk(className="Idle")
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]  File
> "/
> Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-
> tk/
> Tkinter.py", line 1645, in __init__
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]
> self._loadtk()
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]  File
> "/
> Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-
> tk/
> Tkinter.py", line 1659, in _loadtk
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]%
> (_tkinter.TK_VERSION, tk_version)
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]
> RuntimeError:
> 23/06/11 19.18.01   [0x0-0x1f61f6].org.python.IDLE[2470]tk.h
> version
> (8.4) doesn't match libtk.a version (8.5)
> 23/06/11 19.18.01   com.apple.launchd.peruser.502[203]
> ([0x0-0x1f61f6].org.python.IDLE[2470]) Exited with exit code: 1
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default value for optional parameters unexpected behaviour?

2011-06-26 Thread Benjamin Kaplan
On Sun, Jun 26, 2011 at 11:28 AM, Marc Aymerich  wrote:
> Hi,
> I'm trying to define a function that has an optional parameter which
> should be an empty list whenever it isn't given. However, it takes as
> value the same value as the last time the function was executed. What
> is the reason of this behaviour? How does python deal with default
> values (i.e. when are they assigned/created)?
>
> Thanks :)
>

So the thing about Python is that you don't actually declare
functions. You create them. def is an executable statement that
creates a function object. Default arguments are part of the function
object, so they get evaluated when the function is created.

>>> foo
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'foo' is not defined
>>> def foo(a = []) :
... a.append(1)
...
>>> foo.func_defaults
([],)
>>> foo()
>>> foo.func_defaults
([1],)
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write file

2011-07-05 Thread Benjamin Kaplan
On Jul 5, 2011 2:28 PM, "miguel olivares varela" 
wrote:
>
>
> Hi,
>
> i got a csv file that i need to modify and create a new one,  i have no
problem to read mi 'test.cvs' which is the source file but when i try to
create a new one with the modifications i only got the first row in my
'out.csv' file.  I think there is somethng wrong in my loop because i can't
put into the rest.
>
>

>
> [here my code:]
>
> import sys
> import csv
> import os
> import glob
> import time
>
> dir_cdr = "/tmp"
> #loop to find files csv in a directory and read thoses files
> for cdr_files_in in glob.glob(os.path.join(dir_cdr, '*.csv') ):
> file_source = open(cdr_files_in, 'r')
> reader = csv.reader(file_source, delimiter=';',
quoting=csv.QUOTE_NONE)
> try:
> for data in reader:
> if data:
> firstname = data[0]
> lastname = data[1]
> date_source = data[2]
> phone = data[3]
> #Date to epoch
>
timestamp=int(time.mktime(time.strptime(date_cdr, "%Y%m%d %H%M%S")))
> fout = open("out.csv", "w")
> print >>fout, lastname, firstname,
timestamp, phone

Do you understand what these next two lines are doing? They are closing the
file and then exiting the program. I'm pretty sure that's not what you want
to do here.

> fout.close()
> sys.exit()
> file_source.close()
> except csv.Error, e:
> print e
> file_source.close()
> sys.exit('file %s, line %d: %s' % (file_source,
reader.line_num, e)
>
> [out.csv]
> Smith John 1296208720 336
>
>
> Could you help me?
>
> Best Regards,
> Miguel
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String concatenation vs. string formatting

2011-07-08 Thread Benjamin Kaplan
On Fri, Jul 8, 2011 at 1:18 PM, Andrew Berg wrote:

> Is it bad practice to use this
> > logger.error(self.preset_file + ' could not be stored - ' +
> > sys.exc_info()[1])
> Instead of this?
> > logger.error('{file} could not be stored -
> > {error}'.format(file=self.preset_file, error=sys.exc_info()[1]))
>
>
> Other than the case where a variable isn't a string (format() converts
> variables to strings, automatically, right?) and when a variable is used
> a bunch of times, concatenation is fine, but somehow, it seems wrong.
> Sorry if this seems a bit silly, but I'm a novice when it comes to
> design. Plus, there's not really supposed to be "more than one way to do
> it" in Python.
>

String formatting is the One Right Way here. It's fine to use string
concatenation for a few things, but the operation is O(n^2) because each
concat occurs one at a time: Python allocates space for a string the size of
the first 2 things, copies the contents over. Then allocate a string the
size of that string plus the third string and copy the contents over. It can
get pretty slow if you're building a really big string With string
formatting, Python creates a single string large enough to copy all the
formatting arguements in and then copies the contents over once.

Also, string formatting (especially using the new syntax like you are) is
much clearer because there's less noise (the quotes all over the place and
the plusses) and it's better for dealing with internationalization if you
need to do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   >