Re: An unusual question...

2011-04-18 Thread harrismh777

Steven D'Aprano wrote:

>  I'm pretty sure I wrote "standard Python" install in one of my replies.

IronPython*is*  standard Python. As are Jython, PyPy and CPython.



This brings up a question I have had for a while; when is PSF going 
to forward PythonX on over to a formal standards committee like ansi or iso?



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


Re: Python IDE/text-editor

2011-04-18 Thread harrismh777

Terry Reedy wrote:

IDLE loses syntax highlighting annoyingly often


Could you exlain?
When does it do that with a file labelled .py?



... never seen this behavior in IDLE with a .py file; not even once.


I take that back... there was the time I tried to run IDLE on the mac 
mini with Apple built-in tcltk on Snow Leopard... 'till I found out that
tk on the mac is not stable with the built-in tcltk... which I found 
very suspicious for Apple's part...


... by the by, if I down-load tcltk from sources and recompile, along 
with Python32 from sources, will things be stable on the mac??



kind regards,
m harris

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


Re: [OT] Free software versus software idea patents

2011-04-18 Thread geremy condra
On Sun, Apr 17, 2011 at 11:29 PM, harrismh777  wrote:



Ok, so, you're basically saying that perfect simulation is not a
requirement for something to 'be mathematics'. I don't think you can
construct a nontrivial model for mathematics without including that,
but I'd be happy to be proven wrong, and if you'll provide your
criteria for the question of what qualifies as 'being mathematics' we
might get somewhere.

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


Re: Python IDE/text-editor

2011-04-18 Thread harrismh777

Jorgen Grahn wrote:

Based on the comments here, it seems that emacs would have to be the

 editor-in-chief for programmers. I currently use SciTE at work; is it
 reasonable to, effectively, bill my employer for the time it'll take
 me to learn emacs?


Editor-in-chief is a bit strong... but many folks that process text 
files use nothing else... programming is just one venue where emacs shines.


I learned vi early on at the IBM lab @Rochester back in the very early 
'90s on the RS6000; IBM's Unix version AIX. Back in the day the machines 
did not have graphics monitors; rather, they used Info Windows like the 
3151 (basically, dumb terminals with RS-232C connection on a short 25 
pin cable).  So, I became proficient at vi and use it profusely even to 
this very day... the ESC key is worn out on my keyboard !  (but, I 
digressed, as usual)


I didn't take the time to learn emacs when I first heard of it because 
it was presented to me as "just another gui editor" with strange meta 
key relationships (and besides, I was told, real men use vi).


I didn't try emacs until I got to know RMS (by reading his books, 
listening to his speeches on-line, interacting on the FSF) and I wanted 
to know a little bit more about how he ticked... how better than to 
learn to use the editor he developed. It was then that I realized that 
this so-called "gui editor" was actually a Lisp environment capable of 
extension and expansion applicable to all sorts of activities from email 
to program development. I have been using emacs ever since and loving it 
too.   Yes, I still use vi and always will.


Having said all of that, I was able to learn emacs 2.3 from the built-in 
tutorial in about an hour (I'm a little slow). Emacs could take a person 
many years to fully master and appreciate, but the basics come pretty 
easily for a good hour's effort and a cup of coffee. Learning how to 
extend its capabilities with Lisp might take a while longer obviously.


Bottom line for my two cents worth here, put emacs in your tool-kit... 
you'll be glad you did it.



kind regards,
m harris


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


Re: [ANN] Python 2.5.6 Release Candidate 1

2011-04-18 Thread Werner F. Bruhin

On 04/17/2011 11:57 PM, "Martin v. Löwis" wrote:


 http://www.python.org/2.5.6

Just FYI, getting a 404 error on the above.

I can see a 2.5.6c1 listes on 
"http://www.python.org/download/releases/2.5/highlights/";  which goes to 
"http://www.python.org/download/releases/2.5.6/";


Werner

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


Re: Make Python "portable" by default! (Re: Python IDE/text-editor)

2011-04-18 Thread Wolfgang Keller
> >> You can't run Python programs without a Python interpreter
> >> installed.
> >
> > Wrong.
> >
> > See e.g. http://www.portablepython.com/
> 
> Uhm... how does that disprove? 

Which part of the word "installed" don't you understand while actually
using it? >;->

> Whatever language you distributed code
> is in, you need something on the computer that can read it. 

The point is that you don't need to _install_ it. If the developer has
a brain.

Sincerely,

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


strange use of %s

2011-04-18 Thread Tracubik
Hi all,
i'm reading a python tutorial in Ubuntu's Full Circle Magazine and i've 
found this strange use of %s:

sql = "SELECT pkid,name,source,servings FROM Recipes WHERE name like '%%%s%
%'" %response

response is a string. I've newbie in sql.

why do the coder use %%%s%% instead of a simple %s?
why he also use the ''?

thanks in advance for you attention/replies

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


Re: Make Python "portable" by default! (Re: Python IDE/text-editor)

2011-04-18 Thread Chris Angelico
On Mon, Apr 18, 2011 at 6:15 PM, Wolfgang Keller  wrote:
> Which part of the word "installed" don't you understand while actually
> using it? >;->

I have various programs which I distribute in zip/tgz format, and also
as a self-extracting executable on Windows. Does this mean they need
to be "installed" only under Windows? No. They need to be installed to
be run, it's just that the installer is unzip or tar.

(FYI, we "installed" a new minister in the church's manse a few weeks
ago. Didn't involve anything more than a mv.)

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Raymond Hettinger
On Apr 16, 1:24 pm, candide  wrote:
> Consider the following code :
>
> # --
> def bool_equivalent(x):
>      return True if x else False

It's faster to write:

def bool_equivalent(x):
return not not x


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


Re: strange use of %s

2011-04-18 Thread Tim Golden

On 18/04/2011 09:29, Tracubik wrote:

Hi all,
i'm reading a python tutorial in Ubuntu's Full Circle Magazine and i've
found this strange use of %s:

sql = "SELECT pkid,name,source,servings FROM Recipes WHERE name like '%%%s%
%'" %response

response is a string. I've newbie in sql.

why do the coder use %%%s%% instead of a simple %s?
why he also use the ''?


Two parts to this answer.

The straightforward one: because the SQL string needs to end
up looking like this: "... WHERE name LIKE '%abcd%'" and
since it's being generated by Python's string substitution,
the surrounding percents need to be doubled up in the original
string to be left as single in the final string.

An alternative in a modern Python might be to use string formatting:
"... WHERE name LIKE '%{}%'".format (response)

HOWEVER... this is not the best way to introduce Python values into
a SQL string. It's better to use the db module's string substitution
flag (often ? or :field or, confusingly, %s). This is because the
approach above lends itself to what's called SQL injection.
Obligatory xkcd reference: http://xkcd.com/327/

The code would be better if written something like this:

  sql = "SELECT ... WHERE name LIKE '%' + ? + '%'"
  q = db.cursor ()
  q.execute (sql, [response])

(The details will vary according to the database being used etc.)

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


Re: strange use of %s

2011-04-18 Thread Chris Angelico
On Mon, Apr 18, 2011 at 6:29 PM, Tracubik  wrote:
> Hi all,
> i'm reading a python tutorial in Ubuntu's Full Circle Magazine and i've
> found this strange use of %s:
>
> sql = "SELECT pkid,name,source,servings FROM Recipes WHERE name like '%%%s%
> %'" %response
>
> response is a string. I've newbie in sql.
>
> why do the coder use %%%s%% instead of a simple %s?
> why he also use the ''?

Python supports printf-style filling-in of strings. Simple example:

print "Hello, %s!" % "world"

You can also use %d for decimal numbers, %x for hex, and so on (%s
means string). One consequence of this is that the percent character
needs to be escaped - so to display a percentage, you would use
something like:

print "Current progress: %d %%" % 72

which will display "Current progress: 72 %". The percent sign outside
the quotes is the operator.

In the SQL example, the response is bracketed by percent signs. So if
response is "beef", the sql variable will be set to "SELECT
pkid,name,source,servings FROM Recipes WHERE name like '%beef%" -
which is the correct SQL syntax to search for the string 'beef'
anywhere inside the name (the percent signs there are like an asterisk
in a glob).

See for instance:
http://docs.python.org/library/stdtypes.html#string-formatting-operations
http://www.w3schools.com/sql/sql_like.asp

There's a serious issue in this code, in that it allows dodgy
responses to embed SQL code. I don't know what your context is, but
embedding what appears to be a user-provided response unsanitized into
an SQL statement is asking for SQL injection exploits down the track.

http://en.wikipedia.org/wiki/SQL_injection

If it's just a toy for demonstrative purposes that's fine, but it's
good to be aware of these issues. Check out the library you're using
for database access; it's quite possible that you'll be able to embed
variable references in a different way, and let the library escape
them for you - otherwise, look for some kind of escape_string
function.

Hope that helps!

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread candide

Le 18/04/2011 10:33, Raymond Hettinger a écrit :


# --
def bool_equivalent(x):
  return True if x else False


It's faster to write:

def bool_equivalent(x):
 return not not x




faster and ... smarter ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: An unusual question...

2011-04-18 Thread wisecracker
Hi Chris...

> It sounds to me like you're trying to pull off a classic buffer
> overrun and remote code execution exploit, in someone else's Python
> program. And all I have to say is Good luck to you.

Talking of nefarious usage...

I wonder what this would do left unchecked on a current machine and current 
Python install...

###

global somestring
somestring = " "

while 1:
#print somestring
somestring = somestring + " "

###



--
73...

Bazza, G0LCU...

Team AMIGA...

http://homepages.tesco.net/wisecracker/

http://main.aminet.net/search?readme=wisecracker

http://mikeos.berlios.de/

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


Re: An unusual question...

2011-04-18 Thread Chris Angelico
On Mon, Apr 18, 2011 at 7:53 PM,   wrote:
> Talking of nefarious usage...
>
> I wonder what this would do left unchecked on a current machine and current 
> Python install...
>
> ###
>
> global somestring
> somestring = " "
>
> while 1:
>        #print somestring
>        somestring = somestring + " "
>
> ###

It'd take a while, but eventually bomb with MemoryError. If instead
you double the string's length with
"somestring=somestring+somestring", it'll bomb a lot quicker.

I know because I tried it. We have an isolation environment in which
we'll be allowing our clients to provide Python scripts - which means
we have to be sure it'll all be safe.

BTW, the point at which it bombs is defined by ulimit/rlimit, unless
you fiddle with the memory allocator. See previous thread on the
subject. :D

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


Re: Make Python "portable" by default! (Re: Python IDE/text-editor)

2011-04-18 Thread flebber
On Apr 18, 6:33 pm, Chris Angelico  wrote:
> On Mon, Apr 18, 2011 at 6:15 PM, Wolfgang Keller  wrote:
> > Which part of the word "installed" don't you understand while actually
> > using it? >;->
>
> I have various programs which I distribute in zip/tgz format, and also
> as a self-extracting executable on Windows. Does this mean they need
> to be "installed" only under Windows? No. They need to be installed to
> be run, it's just that the installer is unzip or tar.
>
> (FYI, we "installed" a new minister in the church's manse a few weeks
> ago. Didn't involve anything more than a mv.)
>
> Chris Angelico

WTF
>it's just that the installer is unzip or tar.
If I take my clothes out of my luggage bag have i just installed them?
Don't think so unless your new minister is wearing them lol.

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Duncan Booth
Steven D'Aprano  wrote:

> So in Python 2.2, Python introduced two new built-in names, True and 
> False, with values 1 and 0 respectively:
> 
> [steve@sylar ~]$ python2.2
> Python 2.2.3 (#1, Aug 12 2010, 01:08:27)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 True, False
> (1, 0)
 type(True)
>
> 

Also in Python 2.2 (and I think earlier but I don't have anything 
earlier to check) there was an interesting property that while all other 
integers from -1 to 99 were optimised to share a single instance, there 
were actually 2 instances of 0 and 1:

Python 2.2.3 (#1, Sep 26 2006, 18:12:26)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2-1 is 1
1
>>> True is 1
0
>>> (True is 1) is 0
0
>>> (True is 1) is False
1

The code for the win32api made use of this fact to determine whether to 
pass int or bool types through to COM methods.

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


Re: Python IDE/text-editor

2011-04-18 Thread Jean-Michel Pichavant

Alec Taylor wrote:

Good Afternoon,

I'm looking for an IDE which offers syntax-highlighting,
code-completion, tabs, an embedded interpreter and which is portable
(for running from USB on Windows).

Here's a mockup of the app I'm looking for: http://i52.tinypic.com/2uojswz.png

Which would you recommend?

Thanks in advance for any suggestions,

Alec Taylor
  

I don't think anyone mentioned Eric.
I'm not using it though, I stick with vim but I heard good things about 
it. I think it's free.


http://eric-ide.python-projects.org/eric-screenshots.html


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


Re: Python IDE/text-editor

2011-04-18 Thread Ton van Vliet
On Sat, 16 Apr 2011 13:20:32 +1000, Alec Taylor
 wrote:

>Good Afternoon,
>
>I'm looking for an IDE which offers syntax-highlighting,
>code-completion, tabs, an embedded interpreter and which is portable
>(for running from USB on Windows).
>
>Here's a mockup of the app I'm looking for: http://i52.tinypic.com/2uojswz.png
>
>Which would you recommend?
>
>Thanks in advance for any suggestions,
>
>Alec Taylor

For the record, do have a look at the Python Toolkit (PTK) project at
http://pythontoolkit.sourceforge.net/

There is a platform independant source (.zip), however wxPython is a
requirement (so possibly not 'exactly' what you are looking for)

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


Re: An unusual question...

2011-04-18 Thread Steven D'Aprano
On Mon, 18 Apr 2011 10:53:00 +0100, wisecracker wrote:

> global somestring
> somestring = " "

You don't need to declare a name in the global scope as global. It just 
is global.


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


How to create a (transparent) decorator with status information?

2011-04-18 Thread Timo Schmiade
Hi all,

I'm currently occupying myself with python's decorators and have some
questions as to their usage. Specifically, I'd like to know how to
design a decorator that maintains a status. Most decorator examples I
encountered use a function as a decorator, naturally being stateless.

Consider the following:

def call_counts(function):
  @functools.wraps(function):
  def wrapper(*args, **kwargs):
# No status, can't count #calls.
return function(*args, **kwargs)
  return wrapper

Thinking object-orientedly, my first idea was to use an object as a
decorator:

class CallCounter:
  def __init__(self, decorated):
self.__function = decorated
self.__numCalls = 0

  def __call__(self, *args, **kwargs):
self.__numCalls += 1
return self.__function(*args, **kwargs)

  # To support decorating member functions
  def __get__(self, obj, objType):
return functools.partial(self.__call__, obj)

This approach however has three problems (let "decorated" be a function
decorated by either call_counts or CallCounter):

* The object is not transparent to the user like call_counts is. E.g.
  help(decorated) will return CallCounter's help and decorated.func_name
  will result in an error although decorated is a function.
* The maintained status is not shared among multiple instances of the
  decorator. This is unproblematic in this case, but might be a problem
  in others (e.g. logging to a file).
* I can't get the information from the decorator, so unless CallCounter
  emits the information on its own somehow (e.g. by using print), the
  decorator is completely pointless.

So, my question is: What would the "pythonic" way to implement a
decorator with status information be? Or am I missing the point of
decorators and am thinking in completely wrong directions?

Thanks in advance!

Kind regards,

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


Re: An unusual question...

2011-04-18 Thread Grant Edwards
On 2011-04-18, harrismh777  wrote:
> Steven D'Aprano wrote:
>>> >  I'm pretty sure I wrote "standard Python" install in one of my replies.
>> IronPython*is*  standard Python. As are Jython, PyPy and CPython.
>>
>
>  This brings up a question I have had for a while; when is PSF going 
> to forward PythonX on over to a formal standards committee like ansi or iso?

Oh please no.  Anything but that.

Seriously.

-- 
Grant Edwards   grant.b.edwardsYow! Hmmm ... an arrogant
  at   bouquet with a subtle
  gmail.comsuggestion of POLYVINYL
   CHLORIDE ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Alec Taylor
Geany I've tried in the past, it's really buggy on my home computer
and at Uni... however from my phone it works wonderfully! (Use it for
C++ projects on Rhobuntu)

Eric 4 was suggested to me on the #python channel on Freenode...
however I've never been able to get it compiled/working. Too many
dependencies I'm guessing...

PTK looks great, and does everything I want (from screenshots).
Unfortunately, it doesn't run on my system; Win7 x64, Python 2.7.1
x64, WxPython 2.8 x64. Install ran as admin.

Emacs and vim still seem like good alternatives, when I get the time.
However, currently have 3 assignments to start and finish so would
like a simple Notepad2 with python interpreter attached (and keyboard
shortcut to run script) type program.

Please continue recommending

Thanks,

Alec Taylor

On Mon, Apr 18, 2011 at 6:13 AM, Westley Martínez  wrote:
> On Sun, 2011-04-17 at 09:08 +1000, Chris Angelico wrote:
>> On Sun, Apr 17, 2011 at 8:31 AM, Westley Martínez  wrote:
>> >
>> > Either way doesn't it require python be installed on the system?
>>
>> Most Python development is going to require that...
>>
>> I'm rather puzzled by this question; I think I've misunderstood it.
>> You can't run Python programs without a Python interpreter installed.
>>
>> Chris Angelico
>
> Didn't the OP ask for a portable system, i.e. you can carry everything
> around on a flash drive and pop it into any computer? Or is he just
> asking that the editor be portable?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Yep, flash-drive portable if you please =]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Andrea Crotti
Alec Taylor  writes:
>
> Emacs and vim still seem like good alternatives, when I get the time.
> However, currently have 3 assignments to start and finish so would
> like a simple Notepad2 with python interpreter attached (and keyboard
> shortcut to run script) type program.
>
> Please continue recommending

I warmly recommend to change posting style, this time you top-posted
*and* also posted below some quoted text.

If you really have to top post (which is normally bad) at least don't
also post below other text, otherwise people will not see what you wrote
below, because they assume that you wrote everything on top.

About the editor keep in mind that if you continue to change program
you'll not surely be faster or more productive ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you advice a Python library to query a lan subnet with SNMP and collect MAC addresses of nodes?

2011-04-18 Thread Aldo Ceccarelli
On Apr 15, 11:00 am, Aldo Ceccarelli 
wrote:
> Hello All,
> in my specific problem I will be happy of a response where possible
> to:
>
> 1. distinguish different operating systems of answering nodes
> 2. collect responses of Wyse thin-clients with "Thin OS" to get node
> name and MAC address in particular
>
> Thanks a lot in advance for any sharing / forward to documentation,
> products in the area.
>
> KR Aldo

Hello and thank you All!
I've solved my problem as follows:
1. installed nmap
2. wrote a python script calling nmap nmap -sP via os.system and
redirecting output to a file
3. read results file and made a further processing to get exact
filtered records with MAC addresses I needed

Kindest regards Aldo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHONPATH

2011-04-18 Thread MRAB

On 18/04/2011 05:37, harrismh777 wrote:
[snip]

In retrospect, in many ways this is why I am relatively patient with the
Python3 development direction. While I think its non-compatibility may
hurt in the short term, the long term goal of stream-lining the language
will make for a much better Python future. Essentially, the python team
said, "Look, python2 sucks... ," and then they went about figuring out
what Python would look like had it been "designed" right in the first
place. Whalla, Python3. So after years and years of practical experience
with the language Python is getting the face lift it deserves, and is
going to be one gorgeous lady when finished.


[snip]
I think you mean "Voilà, Python3."

And I doubt that the Python team said "Look, python2 sucks...", but
rather "Look, Python2 has some cruft which needs to be removed".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-18 Thread Aahz
In article ,
D'Arcy J.M. Cain  wrote:
>On Sun, 17 Apr 2011 16:21:53 +1200
>Gregory Ewing  wrote:
>> My idiom for fetching from a cache looks like this:
>> 
>>def get_from_cache(x):
>>  y = cache.get(x)
>>  if not y:
>>y = compute_from(x)
>>cache[x] = y
>>  return y
>
>I prefer not to create and destroy objects needlessly.
>
> def get_from_cache(x):
>   if not x in cache:
> cache[x] = compute_from(x)
>   return cache[x]

Aside from Steven's entirely appropriate pointed question, I find this
more readable:

if x not in cache:

Without testing, I'm not sure, but I believe it's more efficient, too
(creates fewer bytecodes).
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-03-22
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Alec Taylor
The current finalists:

*Editra* with PyShell in Shelf

Pros: Syntax highlighting, tabs, ¿portable? and embedded python interpreter
(PyShell 0.8)
Cons: No run button or keyboard shortcut for quick running of script (made
issue: http://code.google.com/p/editra/issues/detail?id=641) and doesn't
save settings changes for editor

*PyScripter*

Pros: Syntax highlighting, tabs, ¿portable?, embedded python interpreter,
keyboard shortcut (Ctrl+F9 [though would prefer single key...]) and run
button
Cons: Unmaintained, so doesn't support x64 and has a few bugs

*UliPad*

Pros: Syntax highlighting, tabs, ¿portable?, embedded python interpreter,
keyboard shortcut (F5) and run button
Cons: Command-prompt window appears whenever script is run (could be admin
issues at Uni) and is unmaintained, so can expect bugs and non-modern
interfaces for length of use

Please continue suggesting Python IDEs and/or fixes for the above Cons.

Thanks,

Alec Taylor

FYI: I can't test Kate, as all the mirrors I've tried have no files on them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Alec Taylor
The current finalists:

Editra with PyShell in Shelf

Pros: Syntax highlighting, tabs, ¿portable? and embedded python
interpreter (PyShell 0.8)
Cons: No run button or keyboard shortcut for quick running of script
(made issue: http://code.google.com/p/editra/issues/detail?id=641) and
doesn't save settings changes for editor

PyScripter

Pros: Syntax highlighting, tabs, ¿portable?, embedded python
interpreter, keyboard shortcut (Ctrl+F9 [though would prefer single
key...]) and run button
Cons: Unmaintained, so doesn't support x64 and has a few bugs

UliPad

Pros: Syntax highlighting, tabs, ¿portable?, embedded python
interpreter, keyboard shortcut (F5) and run button
Cons: Command-prompt window appears whenever script is run (could be
admin issues at Uni) and is unmaintained, so can expect bugs and
non-modern interfaces for length of use

Please continue suggesting Python IDEs and/or fixes for the above Cons.

Thanks,

Alec Taylor

FYI: I can't test Kate, as all the mirrors I've tried have no files on them.
-- 
http://mail.python.org/mailman/listinfo/python-list


installing setuptools on Windows custom python install

2011-04-18 Thread Eric Frederich
Hello,

I have a python installation that I built myself using Visual Studio 2005.
I need this version because I need to link Python bindings to a 3rd
party library that uses VS 2005.

I want to get setuptools installed to this Python installation but the
installer won't find my version of Python even if it is on the PATH
and PYTHONHOME is set.
So, I am trying to build setuptools but when I run "python setup.py
install" I get the following error.
Any ideas either on how to get the installer to find my installation
or on how to get this to compile?

F:\pyside\setuptools-0.6c11>python setup.py install
running install
Traceback (most recent call last):
  File "setup.py", line 94, in 
scripts = scripts,
  File "F:\My_Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
  File "F:\My_Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
  File "F:\My_Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
  File "F:\pyside\setuptools-0.6c11\setuptools\command\install.py",
line 76, in run
self.do_egg_install()
  File "F:\pyside\setuptools-0.6c11\setuptools\command\install.py",
line 85, in do_egg_install
easy_install = self.distribution.get_command_class('easy_install')
  File "F:\pyside\setuptools-0.6c11\setuptools\dist.py", line 395, in
get_command_class
self.cmdclass[command] = cmdclass = ep.load()
  File "F:\pyside\setuptools-0.6c11\pkg_resources.py", line 1954, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "F:\pyside\setuptools-0.6c11\setuptools\command\easy_install.py",
line 21, in 
from setuptools.package_index import PackageIndex, parse_bdist_wininst
  File "F:\pyside\setuptools-0.6c11\setuptools\package_index.py", line
2, in 
import sys, os.path, re, urlparse, urllib2, shutil, random,
socket, cStringIO
  File "F:\My_Python27\lib\urllib2.py", line 94, in 
import httplib
  File "F:\My_Python27\lib\httplib.py", line 71, in 
import socket
  File "F:\My_Python27\lib\socket.py", line 47, in 
import _socket
ImportError: No module named _socket

F:\pyside\setuptools-0.6c11>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing setuptools on Windows custom python install

2011-04-18 Thread Benjamin Kaplan
On Apr 18, 2011 12:55 PM, "Eric Frederich"  wrote:
>
> Hello,
>
> I have a python installation that I built myself using Visual Studio 2005.
> I need this version because I need to link Python bindings to a 3rd
> party library that uses VS 2005.
>
> I want to get setuptools installed to this Python installation but the
> installer won't find my version of Python even if it is on the PATH
> and PYTHONHOME is set.
> So, I am trying to build setuptools but when I run "python setup.py
> install" I get the following error.
> Any ideas either on how to get the installer to find my installation
> or on how to get this to compile?
>
> F:\pyside\setuptools-0.6c11>python setup.py install
> running install
> Traceback (most recent call last):
>  File "setup.py", line 94, in 
>scripts = scripts,
>  File "F:\My_Python27\lib\distutils\core.py", line 152, in setup
>dist.run_commands()
>  File "F:\My_Python27\lib\distutils\dist.py", line 953, in run_commands
>self.run_command(cmd)
>  File "F:\My_Python27\lib\distutils\dist.py", line 972, in run_command
>cmd_obj.run()
>  File "F:\pyside\setuptools-0.6c11\setuptools\command\install.py",
> line 76, in run
>self.do_egg_install()
>  File "F:\pyside\setuptools-0.6c11\setuptools\command\install.py",
> line 85, in do_egg_install
>easy_install = self.distribution.get_command_class('easy_install')
>  File "F:\pyside\setuptools-0.6c11\setuptools\dist.py", line 395, in
> get_command_class
>self.cmdclass[command] = cmdclass = ep.load()
>  File "F:\pyside\setuptools-0.6c11\pkg_resources.py", line 1954, in load
>entry = __import__(self.module_name, globals(),globals(), ['__name__'])
>  File "F:\pyside\setuptools-0.6c11\setuptools\command\easy_install.py",
> line 21, in 
>from setuptools.package_index import PackageIndex, parse_bdist_wininst
>  File "F:\pyside\setuptools-0.6c11\setuptools\package_index.py", line
> 2, in 
>import sys, os.path, re, urlparse, urllib2, shutil, random,
> socket, cStringIO
>  File "F:\My_Python27\lib\urllib2.py", line 94, in 
>import httplib
>  File "F:\My_Python27\lib\httplib.py", line 71, in 
>import socket
>  File "F:\My_Python27\lib\socket.py", line 47, in 
>import _socket
> ImportError: No module named _socket
>

Like the error says, you don't have socket built. Python is very modular.
Just because you built the core doesn't mean you've built every module (and
in fact you cannot build every module in the standard library because some
of them only build on specific OSes).

You'll need to rebuild Python with the socket module in order to use
setuptools. I'm not entirely sure what the Windows dependencies are for
that, so I'll let someone more familiar with the windows build answer that.

> F:\pyside\setuptools-0.6c11>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing setuptools on Windows custom python install

2011-04-18 Thread Wolfgang Rohdewald
On Montag 18 April 2011, Eric Frederich wrote:
>   File "F:\My_Python27\lib\socket.py", line 47, in 
> import _socket
> ImportError: No module named _socket
> 
> F:\pyside\setuptools-0.6c11>

I have C:\Python27

and within that, DLLS\_socket.pyd

this is what import _socket should find

do you have that?

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


Re: How to create a (transparent) decorator with status information?

2011-04-18 Thread Ian Kelly
On Mon, Apr 18, 2011 at 6:47 AM, Timo Schmiade  wrote:
> Hi all,
>
> I'm currently occupying myself with python's decorators and have some
> questions as to their usage. Specifically, I'd like to know how to
> design a decorator that maintains a status. Most decorator examples I
> encountered use a function as a decorator, naturally being stateless.
>
> Consider the following:
>
> def call_counts(function):
>  @functools.wraps(function):
>  def wrapper(*args, **kwargs):
>    # No status, can't count #calls.
>    return function(*args, **kwargs)
>  return wrapper

In the simple case, just store the state on the wrapper function itself:

def call_counts(function):
  @functools.wraps(function)
  def wrapper(*args, **kwargs):
wrapper.num_calls += 1
return function(*args, **kwargs)
  wrapper.num_calls = 0
  return wrapper

@call_counts
def f():
  pass

f()
f()
print(f.num_calls)

> * The maintained status is not shared among multiple instances of the
>  decorator. This is unproblematic in this case, but might be a problem
>  in others (e.g. logging to a file).

If you want the state to be shared, you should probably store it in an
object and use an instance method as the decorator:

class CallCounter(object):
  def __init__(self):
self.num_calls = 0
  def call_counts(self, function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
  self.num_calls += 1
  return function(*args, **kwargs)
return wrapper

call_counter = CallCounter()
@call_counter.call_counts
def f1_with_shared_counts():
  pass

@call_counter.call_counts
def f2_with_shared_counts():
  pass

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you advice a Python library to query a lan subnet with SNMP and collect MAC addresses of nodes?

2011-04-18 Thread Chris Angelico
On Tue, Apr 19, 2011 at 1:23 AM, Aldo Ceccarelli
 wrote:
> Hello and thank you All!
> I've solved my problem as follows:
> 1. installed nmap
> 2. wrote a python script calling nmap nmap -sP via os.system and
> redirecting output to a file
> 3. read results file and made a further processing to get exact
> filtered records with MAC addresses I needed

I don't know if it's significant, but if I want to process a command's
output using Python, I'll generally use:

nmap -sP | /path/to/script.py

rather than os.system() and temporary files. YMMV though.

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread John Nagle

On 4/17/2011 5:12 PM, Gregory Ewing wrote:

Chris Angelico wrote:


Well, of course you can always implement bool as an int;


Which Python used to do once upon a time -- and still does
in a way, because bool is a subclass of int.

The bool type was added mainly to provide a type that prints
out as 'True' or 'False' rather than 1 or 0. This can be
a considerable help for debugging and keeping the conceptual
meaning of one's data clear.


   This is typical for languages which backed into a "bool" type,
rather than having one designed in.  The usual result is a boolean
type with numerical semantics, like

>>> True + True
2

which ought to either generate a TypeError or be interpreted
as "or", but due to the legacy botch, does not.

   Pascal got this right.  (A nice feature of Pascal
was that "packed array of boolean" was a bit array).
C, which originally lacked a "bool" type, got it wrong.
So did Python.  Java is in the middle, with an isolated
"boolean" type but a system that allows casts.

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


logger warning doesn't appear even though propagate flag is True

2011-04-18 Thread Disc Magnet
This program prints both the warnings:

#!/usr/bin/env python2.7

import logging
import logging.config

logging.config.fileConfig('log.conf')

log1 = logging.getLogger()
log2 = logging.getLogger('foo.bar')
log2.addHandler(logging.NullHandler())

log1.warn('warning 1')
log2.warn('warning 2')

However, this prints only the first warning:

#!/usr/bin/env python2.7

import logging
import logging.config

log2 = logging.getLogger('foo.bar')
logging.config.fileConfig('log.conf')

log1 = logging.getLogger()
log2.addHandler(logging.NullHandler())

log1.warn('warning 1')
log2.warn('warning 2')

My log.conf file is defined as:


[loggers]
keys=root

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s %(name)s %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

Could you please explain why the second warning doesn't appear in the
second program?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.5.6 Release Candidate 1

2011-04-18 Thread Martin v. Loewis
Am 18.04.2011 09:59, schrieb Werner F. Bruhin:
> On 04/17/2011 11:57 PM, "Martin v. Löwis" wrote:
>>
>>  http://www.python.org/2.5.6
> Just FYI, getting a 404 error on the above.

Thanks. There had been a number of glitches which have been
corrected. If anything looks still incorrect, please let me know.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you advice a Python library to query a lan subnet with SNMP and collect MAC addresses of nodes?

2011-04-18 Thread Daniel Kluev
Isn't it better to use subprocess.Popen and read stdout/stderr
directly? Should be much more convenient than temporary files.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Two similar logging programs but different ouputs

2011-04-18 Thread Disc Magnet
I have tried writing two programs which are doing similar activities.
The little difference between the two programs is that the first one
configures logger1 using addHandler() method while the second program
configures logger1 from log.conf file.

However, the output differs for both. The first program displays
warnings from both logger1 and logger2. The second program displays
warning from logger1 only. It does not display the warning from
logger2.

Could you please help me understand this difference? Programs and
log.conf file follow:

#!/usr/bin/env python2.7

# This program prints both the warnings
import logging

# Create loggers
logger1 = logging.getLogger()
logger2 = logging.getLogger('foo.bar')

# Configure both loggers
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(name)s %(levelname)s %(message)s'))
logger1.addHandler(handler)
logger2.addHandler(logging.NullHandler())

# Use both loggers
logger1.warn('warning 1')
logger2.warn('warning 2')

#--

#!/usr/bin/env python2.7

# This program prints only the first warning

import logging
import logging.config

# Create loggers
logger1 = logging.getLogger()
logger2 = logging.getLogger('foo.bar')

# Configure root loggers
logging.config.fileConfig('log.conf')
logger2.addHandler(logging.NullHandler())

# Use both loggers
logger1.warn('warning 1')
logger2.warn('warning 2')

#---

"""The file 'log.conf' is as follows:

[loggers]
keys=root

[handlers]
keys=streamHandler

[formatters]
keys=simpleFormatter

[logger_root]
handlers=streamHandler

[handler_streamHandler]
class=StreamHandler
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(name)s %(levelname)s %(message)s
"""

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


Re: Two similar logging programs but different ouputs

2011-04-18 Thread Vinay Sajip
On Apr 18, 10:11 pm, Disc Magnet  wrote:

> Could you please help me understand this difference? Programs and
> log.conf file follow:

The first program prints two messages because loggers pass events to
handlers attached to themselves and their ancestors. Hence, logger1's
message is printed by logger1's handler, and logger2's message is
printed by logger1's handler because it is an ancestor of logger2.

In the second case, logger foo.bar exists when fileConfig() is
called,  but it is not named explicitly in the configuration. Hence,
it is disabled (as documented). Hence only logger1's message is
printed.

NullHandler is a handler which does nothing - there is no point in
adding it to a system which configures logging, and only any point in
adding it to top-level loggers of libraries which may be used when
logging is configured (also documented).

Regards,

Vinay Sajip
Regards,

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


Re: Two similar logging programs but different ouputs

2011-04-18 Thread Vinay Sajip
On Apr 18, 10:11 pm, Disc Magnet  wrote:

> Could you please help me understand this difference? Programs and
> log.conf file follow:

The first program prints two messages because loggers pass events to
handlers attached to themselves and their ancestors. Hence, logger1's
message is printed by logger1's handler, and logger2's message is
printed by logger1's handler because logger1 is an ancestor of
logger2.

In the second case, logger foo.bar exists when fileConfig() is
called,  but it is not named explicitly in the configuration. Hence,
it is disabled (as documented). Hence only logger1's message is
printed.

NullHandler is a handler which does nothing - there is no point in
adding it to a system which configures logging, and only any point in
adding it to top-level loggers of libraries which may be used when
logging is not configured by the using application (this is also
documented).

Regards,

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


Programmatically log in and request XML

2011-04-18 Thread Tim Johnson
FYI: Using python 2.7 on ubuntu 10.04.

I have acquainted myself with the parsing of XML data using an input file as
test data. Now I need to make a request the feed itself, and capture
that field as data.

I need to do the following:
1)Programmatically log into a site with user and password.
2)Make a GET request to a site under the same domain.

Since I have used urllib2 in the past,
>From http://docs.python.org/library/urllib2.html
I am offering a modification of the example under the heading:
"""
Use of Basic HTTP Authentication
"""
import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm=None,
  uri='http://retsgw.flexmls.com:80/rets2_0/Login',
  user='**',
  passwd='**')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://retsgw.flexmls.com/rets2_0/GetMetadata?Type=METADATA-TABLE&ID=Property:A&Format=STANDARD-XML')

Am I at the correct starting point? 
  If so, I can take it from there
If not,
  Can someone recommend a better approach?

thanks
-- 
Tim 
tim at johnsons-web dot com or akwebsoft dot com
http://www.akwebsoft.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An unusual question...

2011-04-18 Thread Rhodri James

On Mon, 18 Apr 2011 08:01:00 +0100,  wrote:


Hi Rhodri...


You do realise that what id() returns is implementation-dependent, don't
you?  In particular, what IronPython returns isn't an address.


I'm pretty sure I wrote "standard Python" install in one of my replies.

Yeah here it is in a reply to Miki...

"Hmm, I was hoping to stay inside a standard Python install."


IronPython *is* a standard Python install.  So is CPython, the one I  
presume you mean.  Even that doesn't offer you any guarantee that it isn't  
going to change what id() returns from one version to the next.  Relying  
on implementation-defined behaviour like this is a good way of getting  
code to blow up in your face.  You'll get much more reliable results by  
starting in a language that was actually intended for direct memory  
access, like C, and wrapping that in Python.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a (transparent) decorator with status information?

2011-04-18 Thread Wayne Witzel III
> 
> Thinking object-orientedly, my first idea was to use an object as a
> decorator:
> 
> class CallCounter:
>   def __init__(self, decorated):
> self.__function = decorated
> self.__numCalls = 0
> 
>   def __call__(self, *args, **kwargs):
> self.__numCalls += 1
> return self.__function(*args, **kwargs)
> 
>   # To support decorating member functions
>   def __get__(self, obj, objType):
> return functools.partial(self.__call__, obj)
> 
> This approach however has three problems (let "decorated" be a function
> decorated by either call_counts or CallCounter):
> 
> * The object is not transparent to the user like call_counts is. E.g.
>   help(decorated) will return CallCounter's help and decorated.func_name
>   will result in an error although decorated is a function.
> * The maintained status is not shared among multiple instances of the
>   decorator. This is unproblematic in this case, but might be a problem
>   in others (e.g. logging to a file).
> * I can't get the information from the decorator, so unless CallCounter
>   emits the information on its own somehow (e.g. by using print), the
>   decorator is completely pointless.
> 

Going with the object approach, you could use Borg to give yourself the state 
between instances you mentioned. And since you are using an object, you'll have 
access to the data without needing to return it from the decorator.

class StatefulDecorators(object):
_state = {}
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._state
return self

def count_calls(self, function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
self.calls += 1
except AttributeError:
self.calls = 1
return function(*args, **kwargs)
return wrapper

>>> sd = StatefulDecorators()
>>> @sd.count_calls
... def test():
... pass
>>> test()
>>> sd.calls
1
>>> sd1 = StatefulDecorators()
>>> @sd1.count_calls
... def test2():
... pass
>>> test2()
>>> sd1.calls
2
>>> sd.calls
2

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


Popen to get stdout and stderr for ffmpeg - No such file or directory ?

2011-04-18 Thread goldtech
Hi,

Trying to learn how to run a linux command and get the stdout and
stderr. I'm trying the following:

>>> cmd3 = r'ffmpeg -i /home/giga/Desktop/Guitar1.flv'
>>> p = Popen(cmd3, stdout=PIPE, stderr=PIPE)

Traceback (most recent call last):
  File "", line 1, in 
p = Popen(cmd3, stdout=PIPE, stderr=PIPE)
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in
_execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

But:

>>> if os.path.exists(r'/home/giga/Desktop/Guitar1.flv'):
print "exist"

exist
>>>

And just running ffmpeg alone seems as expected:

>>> cmd2=r'ffmpeg'
>>> p = Popen(cmd2, stdout=PIPE, stderr=PIPE)
>>> stdout, stderr = p.communicate()
>>> stdout
'Hyper fast Audio and Video encoder\nusage: ffmpeg [options] [[infile
options] -i infile]... {[outfile options] outfile}...\n\n'
>>> stderr
"FFmpeg version git-N-29152-g0ba8485, Copyright (c) 2000-2011 the
FFmpeg developers\n  built on Apr 16 2011 16:40:56 with gcc 4.4.5\n
configuration: --enable-gpl ...snip...

Also if I run the exact command (cmd3) in the terminal it works OK.
Why is it not finding the file? Thanks, help appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python3 "designed right" (was: PYTHONPATH)

2011-04-18 Thread Brendan Simon (eTRIX)

On 19/04/2011 2:15 AM, python-list-requ...@python.org wrote:

Subject:
Re: PYTHONPATH
From:
MRAB 
Date:
Mon, 18 Apr 2011 16:31:31 +0100

To:
python-list@python.org


On 18/04/2011 05:37, harrismh777 wrote:
[snip]

In retrospect, in many ways this is why I am relatively patient with the
Python3 development direction. While I think its non-compatibility may
hurt in the short term, the long term goal of stream-lining the language
will make for a much better Python future. Essentially, the python team
said, "Look, python2 sucks... ," and then they went about figuring out
what Python would look like had it been "designed" right in the first
place. Whalla, Python3. So after years and years of practical experience
with the language Python is getting the face lift it deserves, and is
going to be one gorgeous lady when finished.


Personally, I really hope Python3 (or 3+) would have some of the 
features that Cobra has built into the language.
  * dynamic/late binding (like Python) for flexibility _and_ 
static/early binding for fast execution and error checking.

  * inbuilt support for quality
- compile time "None Error" tracking# I have experienced this a 
lot and it's a real pain :(

- inbuilt unit testing
- inbuilt "contracts" to ensure conditions are met when calling 
functions.

  * no "self"
  * no ":" after if/else statements.

My main gripe with Cobra is that it requires the .NET framework (or 
Mono), though the web pages do suggest they are also working on a 
version that runs on JVM.  Also third party libraries (e.g GUIs like wx) 
may not be as good or available (yet) ??


http://cobra-language.com/docs/python/
http://cobra-language.com/docs/why/

-- Brendan.

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


Re: [ANN] Python 2.5.6 Release Candidate 1

2011-04-18 Thread Brendan Simon (eTRIX)

On 19/04/2011 9:05 AM, python-list-requ...@python.org wrote:


Am 18.04.2011 09:59, schrieb Werner F. Bruhin:

>  On 04/17/2011 11:57 PM, "Martin v. Löwis" wrote:

>>http://www.python.org/2.5.6
If there is an official release of source (e.g. 2.5.5 and 2.5.6) why 
aren't binaries produced (other than to make it really hard for users 
and force them to upgrade to a later major revision -- 2.6, 2.7, etc) ??


It's ok for Linux distros as they tend to build from sources, and test, 
and produce their own binary packages.  But for OS X and MSW users it's 
not quite like that.  I'd like to upgrade to 2.5.6 (for one particular 
mature application), but unfortunately I'm stuck with 2.5.4 as I don't 
really want to have to build (and hopefully get it right) on my OS X box.


Cheers, Brendan.

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


Re: Popen to get stdout and stderr for ffmpeg - No such file or directory ?

2011-04-18 Thread Chris Rebert
On Mon, Apr 18, 2011 at 4:07 PM, goldtech  wrote:
> Hi,
>
> Trying to learn how to run a linux command and get the stdout and
> stderr. I'm trying the following:
>
 cmd3 = r'ffmpeg -i /home/giga/Desktop/Guitar1.flv'
 p = Popen(cmd3, stdout=PIPE, stderr=PIPE)
>
> Traceback (most recent call last):
>  File "", line 1, in 
>    p = Popen(cmd3, stdout=PIPE, stderr=PIPE)
>  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
>    errread, errwrite)
>  File "/usr/lib/python2.6/subprocess.py", line 1141, in
> _execute_child
>    raise child_exception
> OSError: [Errno 2] No such file or directory
>
> But:
>
 if os.path.exists(r'/home/giga/Desktop/Guitar1.flv'):
>        print "exist"

> Also if I run the exact command (cmd3) in the terminal it works OK.
> Why is it not finding the file? Thanks, help appreciated.

Read The Fine Manual:
http://docs.python.org/library/subprocess.html#subprocess.Popen :
"On Unix, with shell=False (default): [...] If a string is specified
for args, it will be used as the name or path of the program to
execute; ***this will only work if the program is being given no
arguments.***" (emphasis added)

The system is interpreting the entire command string as the path to an
executable; obviously there's no directory named "ffmpeg -i ", so the
path is invalid, hence the error.

Try instead:
cmd3 = ['ffmpeg', '-i', '/home/giga/Desktop/Guitar1.flv']

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Popen to get stdout and stderr for ffmpeg - No such file or directory ?

2011-04-18 Thread Rhodri James
On Tue, 19 Apr 2011 00:07:46 +0100, goldtech   
wrote:



Trying to learn how to run a linux command and get the stdout and
stderr. I'm trying the following:


cmd3 = r'ffmpeg -i /home/giga/Desktop/Guitar1.flv'
p = Popen(cmd3, stdout=PIPE, stderr=PIPE)


Traceback (most recent call last):
  File "", line 1, in 
p = Popen(cmd3, stdout=PIPE, stderr=PIPE)
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in
_execute_child
raise child_exception
OSError: [Errno 2] No such file or directory



This is something that catches everyone!  From the Fine Manual  
(http://docs.python.org/library/subprocess.html#using-the-subprocess-module):



On Unix, with shell=False (default): In this case, the Popen class
uses os.execvp() to execute the child program. args should normally
be a sequence. If a string is specified for args, it will be used
as the name or path of the program to execute; this will only work
if the program is being given no arguments.


What you actually want is more like:

p = Popen(('ffmpeg', '-i', '/home/giga/Desktop/Guitar1.flv'),
  stdout=PIPE, stderr=PIPE)

The manual gives you an example of using shlex to split a string
into tokens if you'd rather do it that way.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Gregory Ewing

John Nagle wrote:

   Pascal got this right.  (A nice feature of Pascal
was that "packed array of boolean" was a bit array).
C, which originally lacked a "bool" type, got it wrong.
So did Python.


If Python had had a boolean type from the beginning, it
probably wouldn't have been a subclass of int -- that was
more or less forced by backwards compatibility issues.


Java is in the middle, with an isolated
"boolean" type but a system that allows casts.


I'm not sure that's all that much different from Pascal,
where you can use ord() to turn a boolean into an int
if you want to. At least you're being explicit.

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Gregory Ewing

Chris Angelico wrote:


Remind me some day to finish work on my "ultimate programming
language", which starts out with a clean slate and lets the programmer
define his own operators and everything.


Didn't someone already do that and call it "lisp"? :-)

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread James Mills
On Tue, Apr 19, 2011 at 10:17 AM, Rance Hall  wrote:
> pseudo code:
>
>
> message = "Bah."
>
> if test:
>   message = message + " Humbug!"
>
> print(message)
>
> end pseudo code

Normally it's considered bad practise to concatenate strings.
Use a a format specifier like this:

> message = "Bah."
>
> if test:
>   message = "%s %s" (message, " Humbug!")
>
> print(message)

Python3 (afaik) also introduced the .format(...) method on strings.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-18 Thread Gregory Ewing

Chris Angelico wrote:


Question: How many factorial functions are implemented because a
program needs to know what n! is, and how many are implemented to
demonstrate recursion (or to demonstrate the difference between
iteration and recursion)? :)


A related question is how often factorial functions are even
*used* in real code.

I can think of two uses for factorials off the top of my
head:

* Coefficients of polynomials resulting from Taylor expansions.
In that case you probably have a loop that's calculating the
numerators and denominators iteratively, and the factorial
is folded into that. Or you're looking up the coefficients in
a table and not calculating factorials at all.

* Combinations and permutations -- again, the factorials are
probably folded into a loop that calculates the result in a
more direct and efficient way.

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Westley Martínez
On Tue, 2011-04-19 at 10:34 +1000, James Mills wrote:
> On Tue, Apr 19, 2011 at 10:17 AM, Rance Hall  wrote:
> > pseudo code:
> >
> >
> > message = "Bah."
> >
> > if test:
> >   message = message + " Humbug!"
> >
> > print(message)
> >
> > end pseudo code
> 
> Normally it's considered bad practise to concatenate strings.
> Use a a format specifier like this:
> 
> > message = "Bah."
> >
> > if test:
> >   message = "%s %s" (message, " Humbug!")
> >
> > print(message)
> 
> Python3 (afaik) also introduced the .format(...) method on strings.
> 
> cheers
> James
> 
> -- 
> -- James Mills
> --
> -- "Problems are solved by method"

How is concatenating strings bad practice?  I use code such as:

string = 'hello'
string += ' children.'

a lot.

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Benjamin Kaplan
On Mon, Apr 18, 2011 at 8:58 PM, Westley Martínez  wrote:
> On Tue, 2011-04-19 at 10:34 +1000, James Mills wrote:
>> On Tue, Apr 19, 2011 at 10:17 AM, Rance Hall  wrote:
>> > pseudo code:
>> >
>> >
>> > message = "Bah."
>> >
>> > if test:
>> >   message = message + " Humbug!"
>> >
>> > print(message)
>> >
>> > end pseudo code
>>
>> Normally it's considered bad practise to concatenate strings.
>> Use a a format specifier like this:
>>
>> > message = "Bah."
>> >
>> > if test:
>> >   message = "%s %s" (message, " Humbug!")
>> >
>> > print(message)
>>
>> Python3 (afaik) also introduced the .format(...) method on strings.
>>
>> cheers
>> James
>>
>> --
>> -- James Mills
>> --
>> -- "Problems are solved by method"
>
> How is concatenating strings bad practice?  I use code such as:
>
> string = 'hello'
> string += ' children.'
>
> a lot.
>

Python's strings are immutable. So adding strings together has to
allocate memory for each intermediate string. Not a big deal if you're
just concatenating two strings, but if you have a whole bunch of long
strings, it's much more efficient and much faster to use string
formatting which just allocates memory for the final string and then
puts everything in.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Christian Heimes
Am 18.04.2011 21:58, schrieb John Nagle:
> This is typical for languages which backed into a "bool" type,
> rather than having one designed in.  The usual result is a boolean
> type with numerical semantics, like
> 
>  >>> True + True
> 2

I find the behavior rather useful. It allows multi-xor tests like:

if a + b + c + d != 1:
raise ValueError("Exactly one of a, b, c or d must be true.")

Christian

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


Re: Questions about GIL and web services from a n00b

2011-04-18 Thread Hank Fay
Today I just happened to watch this session from PyCon 2011 on gevent and 
gunicorn: http://blip.tv/file/4883016  gevent uses greenlet, fwiw. I found it 
informative, but then I find most things informative. 

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Westley Martínez
On Mon, 2011-04-18 at 21:23 -0400, Benjamin Kaplan wrote:
> message = "%s %s" % (message, " Humbug!")
fix'd

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Steven D'Aprano
On Tue, 19 Apr 2011 10:34:27 +1000, James Mills wrote:

> Normally it's considered bad practise to concatenate strings. 

*Repeatedly*.

There's nothing wrong with concatenating (say) two or three strings. 
What's a bad idea is something like:


s = ''
while condition:
s += "append stuff to end"

Even worse:

s = ''
while condition:
s = "insert stuff at beginning" + s

because that defeats the runtime optimization (CPython only!) that 
*sometimes* can alleviate the badness of repeated string concatenation.

See Joel on Software for more:

http://www.joelonsoftware.com/articles/fog000319.html

But a single concatenation is more or less equally efficient as string 
formatting operations (and probably more efficient, because you don't 
have the overheard of parsing the format mini-language).

For repeated concatenation, the usual idiom is to collect all the 
substrings in a list, then join them all at once at the end:

pieces = []
while condition:
pieces.append('append stuff at end')
s = ''.join(pieces)




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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Dan Stromberg
On Mon, Apr 18, 2011 at 6:23 PM, Benjamin Kaplan
 wrote:
> On Mon, Apr 18, 2011 at 8:58 PM, Westley Martínez  wrote:
>> On Tue, 2011-04-19 at 10:34 +1000, James Mills wrote:
>>> On Tue, Apr 19, 2011 at 10:17 AM, Rance Hall  wrote:
>>> > pseudo code:
>>> >
>>> >
>>> > message = "Bah."
>>> >
>>> > if test:
>>> >   message = message + " Humbug!"
>>> >
>>> > print(message)
>>> >
>>> > end pseudo code
>>>
>>> Normally it's considered bad practise to concatenate strings.
>>> Use a a format specifier like this:
>>>
>>> > message = "Bah."
>>> >
>>> > if test:
>>> >   message = "%s %s" (message, " Humbug!")
>>> >
>>> > print(message)
>>>
>>> Python3 (afaik) also introduced the .format(...) method on strings.
>>>
>>> cheers
>>> James
>>>
>>> --
>>> -- James Mills
>>> --
>>> -- "Problems are solved by method"
>>
>> How is concatenating strings bad practice?  I use code such as:
>>
>> string = 'hello'
>> string += ' children.'
>>
>> a lot.
>>
>
> Python's strings are immutable. So adding strings together has to
> allocate memory for each intermediate string. Not a big deal if you're
> just concatenating two strings, but if you have a whole bunch of long
> strings, it's much more efficient and much faster to use string
> formatting which just allocates memory for the final string and then
> puts everything in.

Agreed, adding two strings is not a big deal.  I think adding
1,000,000 strings Can be, but may not be.

ISTR that in some Python runtimes, adding n strings using + is O(n),
while in others it's O(n^2).  Needless to say, that's a pretty big
difference.

This is where the common ''.join(list_) stuff comes from - you put
your substrings in a list and join them with a separator of an empty
string.  This may actually be slower than repeated += in some
runtimes, but its guaranteed to be reasonable asymptotically speaking.

I actually find a + b a little more readable than '%s%s' % (a, b), but
the latter is less likely to need to be rearranged later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.5.6 Release Candidate 1

2011-04-18 Thread Terry Reedy

On 4/18/2011 7:33 PM, Brendan Simon (eTRIX) wrote:


If there is an official release of source (e.g. 2.5.5 and 2.5.6) why
aren't binaries produced (other than to make it really hard for users
and force them to upgrade to a later major revision -- 2.6, 2.7, etc) ??


Unofficial answer:
A. Binaries are a lot of work.
B. Security releases are primarily for servers.
C. Security releases after bugfix is over is better than nothing (the 
old policy before 2.5).

D. You are welcome to pay someone to produce one for you.

--
Terry Jan Reedy

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


Re: Popen to get stdout and stderr for ffmpeg - No such file or directory ?

2011-04-18 Thread goldtech

> Read The Fine 
> Manual:http://docs.python.org/library/subprocess.html#subprocess.Popen:

snip...
>
> Try instead:
> cmd3 = ['ffmpeg', '-i', '/home/giga/Desktop/Guitar1.flv']
>
> Cheers,
> Chris
> --http://blog.rebertia.com

No doubt, I should RTFM...you're right!

Yes, works like a charm now.

Thanks so much for the help. I really appreciate it!
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: [Tutor] working with strings in python3

2011-04-18 Thread Chris Angelico
On Tue, Apr 19, 2011 at 12:16 PM, Steven D'Aprano
 wrote:
> See Joel on Software for more:
>
> http://www.joelonsoftware.com/articles/fog000319.html

The bulk of that article is reasonable; he's right in that a good
programmer MUST have at least some understanding of what's happening
on the lowest level. He seems to consider C strings to be
fundamentally bad, though; which isn't quite fair. See, a C-style
ASCIIZ string can scale up to infinity - the Pascal strings he
mentions are limited to 255 bytes, and while a forward-thinker might
have gone as far as a 32-bit length (not guaranteed, and quite
wasteful if you have billions of short strings - imagine if your
32-bit arithmetic functions are double effort for the CPU), in today's
world it's not that uncommon to work with 4GB or more of data. ASCIIZ
may not be the most efficient for strcatting onto, but you shouldn't
strcat in a loop like that anyway; rather than the mystrcat that he
offered, it's better to have a mystrcpy (called strmov in several
libraries) that's identical to strcpy but returns the end of the
string. Identical to his version but without the dest++ scan first,
and used in the same way but without bothering to put the starting \0
in the buffer.

Ultimately, though, every method of joining strings is going to have
to deal with the "first strlen, then strcpy" issue. I haven't looked
at Python's guts, but I would expect that list joining does this; and
one of the simplest ways to code a StringBuffer object (which I've
used on occasion in raw C) is to simply save all the pointers and then
build the string at the end, which is really the same as
"".join(list). (And yes, I know this depends on the memory still being
allocated. I knew what I was doing when I took that shortcut.)

"Anyway. Life just gets messier and messier down here in byte-land.
Aren't you glad you don't have to write in C anymore?"

Nope. I'm glad that I *can* write in C still. Well, actually I use C++
because I prefer the syntax, but there are plenty of times when I want
that down-on-the-metal coding.

Oh, and by the way. XML sucks if you want performance... and it's so
easy to abuse that I don't really see that it has much value for "data
structures" outside of file transfers. You package your data up in
XML, send it to the other end, they unpack it and turn it into what
they want. End of XMLness. And if you want anything binary ("hey guys,
here's the icon that I want you to display with this thing", for
instance), it gets messier. Much neater to avoid it altogether.

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


Re: [Tutor] working with strings in python3

2011-04-18 Thread Westley Martínez
On Tue, 2011-04-19 at 02:16 +, Steven D'Aprano wrote:
> On Tue, 19 Apr 2011 10:34:27 +1000, James Mills wrote:
> 
> > Normally it's considered bad practise to concatenate strings. 
> 
> *Repeatedly*.
> 
> There's nothing wrong with concatenating (say) two or three strings. 
> What's a bad idea is something like:
> 
> 
> s = ''
> while condition:
> s += "append stuff to end"
> 
> Even worse:
> 
> s = ''
> while condition:
> s = "insert stuff at beginning" + s
> 
> because that defeats the runtime optimization (CPython only!) that 
> *sometimes* can alleviate the badness of repeated string concatenation.
> 
> See Joel on Software for more:
> 
> http://www.joelonsoftware.com/articles/fog000319.html
> 
> But a single concatenation is more or less equally efficient as string 
> formatting operations (and probably more efficient, because you don't 
> have the overheard of parsing the format mini-language).
> 
> For repeated concatenation, the usual idiom is to collect all the 
> substrings in a list, then join them all at once at the end:
> 
> pieces = []
> while condition:
> pieces.append('append stuff at end')
> s = ''.join(pieces)
> 
> 
> 
> 
> -- 
> Steven

Thanks Steven, I was about to ask for an efficient way to concatenate an
arbitrary amount of strings.

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


Re: Python IDE/text-editor

2011-04-18 Thread Alec Taylor
SPE looks good, however I couldn't get it running (svn'd it). Do you
know if there's an installer?

Editra has a really active support team, and have addressed all 3 of
the bugs I found. (although mostly the bugs were me not knowing how it
works!)

Code completion would be nice, especially for a beginner like
myself... so I'll continue looking at the competition.

Please continue with your recommendations.

Thanks,

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


Re: Python IDE/text-editor

2011-04-18 Thread Teemu Likonen
* 2011-04-19T00:40:09+10:00 * Alec Taylor wrote:
> Please continue recommending

Emacs.

* 2011-04-19T02:41:11+10:00 * Alec Taylor wrote:
> Please continue suggesting Python IDEs and/or fixes for the above
> Cons.

Emacs.

* 2011-04-19T13:44:29+10:00 * Alec Taylor wrote:
> Please continue with your recommendations.

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


IDLE bug

2011-04-18 Thread harrismh777

Are bug reports wanted here, or just in issue tracker?

thanks

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


Re: IDLE bug

2011-04-18 Thread James Mills
On Tue, Apr 19, 2011 at 2:05 PM, harrismh777  wrote:
> Are bug reports wanted here, or just in issue tracker?

Pretty sure they're wanted in the Issue Tracker.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Westley Martínez
On Tue, 2011-04-19 at 06:51 +0300, Teemu Likonen wrote:
> * 2011-04-19T00:40:09+10:00 * Alec Taylor wrote:
> > Please continue recommending
> 
> Vim.
> 
> * 2011-04-19T02:41:11+10:00 * Alec Taylor wrote:
> > Please continue suggesting Python IDEs and/or fixes for the above
> > Cons.
> 
> Vim.
> 
> * 2011-04-19T13:44:29+10:00 * Alec Taylor wrote:
> > Please continue with your recommendations.
> 
> Vim.

/trollface.jpg

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


Re: IDLE bug

2011-04-18 Thread Westley Martínez
On Mon, 2011-04-18 at 23:05 -0500, harrismh777 wrote:
> Are bug reports wanted here, or just in issue tracker?
> 
> thanks
> 

If it's a super-critical bug that can destroy data, yes, else just the
issue tracker.

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


Re: Python IDE/text-editor

2011-04-18 Thread Ben Finney
Alec Taylor  writes:

> Please continue with your recommendations.

At some point you need to act on these recommendations by picking one
for the time being.

If you're so tight for time, why are you still evaluating editors after
several days of recommendations? Why have you not yet chosen an editor
and moved on with the work you need to do in it?

-- 
 \  “One bad programmer can easily create two new jobs a year. |
  `\  Hiring more bad programmers will just increase our perceived |
_o__) need for them.” —David Lorge Parnas, 1999-03 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread rusi
On Tue, 2011-04-19 at 06:51 +0300, Teemu Likonen wrote:
emacs * 3

On Apr 19, 9:17 am, Westley Martínez  wrote:
vi * 3

This would be a competition except for viper:
http://www.emacswiki.org/emacs/ViperMode
IOW emacs can be morphed into vi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread Chris Angelico
On Tue, Apr 19, 2011 at 2:37 PM, rusi  wrote:
> On Tue, 2011-04-19 at 06:51 +0300, Teemu Likonen wrote:
> emacs * 3
>
> On Apr 19, 9:17 am, Westley Martínez  wrote:
> vi * 3
>
> This would be a competition except for viper:
> http://www.emacswiki.org/emacs/ViperMode
> IOW emacs can be morphed into vi

The emacs-vi wars... where the men were real men, the women were real
women, and vi was just emacs in disguise...

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


Re: Python IDE/text-editor

2011-04-18 Thread rusi
On Apr 19, 9:32 am, Ben Finney  wrote:
> Alec Taylor  writes:
> > Please continue with your recommendations.
>
> At some point you need to act on these recommendations by picking one
> for the time being.
>
> If you're so tight for time, why are you still evaluating editors after
> several days of recommendations? Why have you not yet chosen an editor
> and moved on with the work you need to do in it?

A good troll is one who is not seen to be one.
However at 83 responses so far he is certainly doing well :-)

>
> --
>  \          “One bad programmer can easily create two new jobs a year. |
>   `\      Hiring more bad programmers will just increase our perceived |
> _o__)                     need for them.” —David Lorge Parnas, 1999-03 |
> Ben Finney

Particularly apt here...
Where do you get these?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-18 Thread rusi
On Apr 19, 9:44 am, Chris Angelico  wrote:
> On Tue, Apr 19, 2011 at 2:37 PM, rusi  wrote:
> > On Tue, 2011-04-19 at 06:51 +0300, Teemu Likonen wrote:
> > emacs * 3
>
> > On Apr 19, 9:17 am, Westley Martínez  wrote:
> > vi * 3
>
> > This would be a competition except for viper:
> >http://www.emacswiki.org/emacs/ViperMode
> > IOW emacs can be morphed into vi
>
> The emacs-vi wars... where the men were real men, the women were real
> women, and vi was just emacs in disguise...
>
> Chris Angelico

So is the real man disguised as a woman?
Or the other way round?

More seriously I should admit to never having used viper :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange use of %s

2011-04-18 Thread Chris Angelico
On Tue, Apr 19, 2011 at 3:22 PM, Dennis Lee Bieber
 wrote:
> On Mon, 18 Apr 2011 09:44:40 +0100, Tim Golden 
> declaimed the following in gmane.comp.python.general:
>
>
>>    sql = "SELECT ... WHERE name LIKE '%' + ? + '%'"
>>    q = db.cursor ()
>>    q.execute (sql, [response])
>>
>        That won't work properly either (at least not in MySQLdb -- which
> quotes the values put into the placeholder; you'd end up with
>        '%''value''%'

You'd end up with "... LIKE '%' + 'value' + '%'" which is perhaps
overkill (it forces the database engine to concatenate three strings),
but at least it's safe.

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


Re: Two similar logging programs but different ouputs

2011-04-18 Thread Disc Magnet
Thank you Vinay for the quick reply. I have a few more questions.

On Tue, Apr 19, 2011 at 3:27 AM, Vinay Sajip  wrote:
> On Apr 18, 10:11 pm, Disc Magnet  wrote:
>
>> Could you please help me understand this difference? Programs and
>> log.conf file follow:
>
> The first program prints two messages because loggers pass events to
> handlers attached to themselves and their ancestors. Hence, logger1's
> message is printed by logger1's handler, and logger2's message is
> printed by logger1's handler because logger1 is an ancestor of
> logger2.
>
> In the second case, logger foo.bar exists when fileConfig() is
> called,  but it is not named explicitly in the configuration. Hence,
> it is disabled (as documented). Hence only logger1's message is
> printed.

I couldn't find this mentioned in the documentation at:

http://docs.python.org/library/logging.config.html#configuration-file-format

Could you please tell me where this is documented?

>
> NullHandler is a handler which does nothing - there is no point in
> adding it to a system which configures logging, and only any point in
> adding it to top-level loggers of libraries which may be used when
> logging is not configured by the using application (this is also
> documented).
>

Actually, I was learning how logging works with NullHandler because I
am going to use it with a library I am writing. The code that I shared
is meant for experimenting. Once, I am comfortable with the logging
API, I'll separate the code into different modules.

In the following code, foo.bar is not explicitly mentioned in the file
configuration. As per what you said, foo.bar should be disabled.
However, I get the following output:

root WARNING warning 1
foo WARNING warning 2
foo WARNING warning 2
foo.bar WARNING warning 3
foo.bar WARNING warning 3

Program and configuration file follow:

#!/usr/bin/env python2.7

# This program prints only the first warning

import logging
import logging.config

# Create loggers
logger1 = logging.getLogger()
logger2 = logging.getLogger('foo')
logger3 = logging.getLogger('foo.bar')

# Configure root loggers
logging.config.fileConfig('log.conf')
logger2.addHandler(logging.NullHandler())
logger3.addHandler(logging.NullHandler())

# Use both loggers
logger1.warn('warning 1')
logger2.warn('warning 2')
logger3.warn('warning 3')

#---

"""The file 'log.conf' is as follows:

[loggers]
keys=root,foo

[handlers]
keys=streamHandler

[formatters]
keys=simpleFormatter

[logger_root]
handlers=streamHandler

[logger_foo]
qualname=foo
handlers=streamHandler

[handler_streamHandler]
class=StreamHandler
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(name)s %(levelname)s %(message)s
"""

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


Re: Can you advice a Python library to query a lan subnet with SNMP and collect MAC addresses of nodes?

2011-04-18 Thread Aldo Ceccarelli
On 18 Apr, 22:38, Daniel Kluev  wrote:
> Isn't it better to use subprocess.Popen and read stdout/stderr
> directly? Should be much more convenient than temporary files.
>
> --
> With best regards,
> Daniel Kluev

Thanks Daniel, your solution is far better WKR! Aldo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Kushal Kumaran
On Tue, Apr 19, 2011 at 7:09 AM, Christian Heimes  wrote:
> Am 18.04.2011 21:58, schrieb John Nagle:
>>     This is typical for languages which backed into a "bool" type,
>> rather than having one designed in.  The usual result is a boolean
>> type with numerical semantics, like
>>
>>  >>> True + True
>> 2
>
> I find the behavior rather useful. It allows multi-xor tests like:
>
> if a + b + c + d != 1:
>    raise ValueError("Exactly one of a, b, c or d must be true.")
>

Unless you're sure all of a, b, c, and d are boolean values, an int
with a negative value slipping in could result in the sum equaling 1,
but more than one of the variables evaluating to True in boolean
contexts.

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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread Chris Angelico
On Tue, Apr 19, 2011 at 4:23 PM, Kushal Kumaran
 wrote:
>> if a + b + c + d != 1:
>>    raise ValueError("Exactly one of a, b, c or d must be true.")
>>
>
> Unless you're sure all of a, b, c, and d are boolean values, an int
> with a negative value slipping in could result in the sum equaling 1,
> but more than one of the variables evaluating to True in boolean
> contexts.

If they're all expressions, then you can easily guarantee that.

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


Re: Feature suggestion -- return if true

2011-04-18 Thread Jussi Piitulainen
Gregory Ewing writes:
> Chris Angelico wrote:
> 
> > Question: How many factorial functions are implemented because a
> > program needs to know what n! is, and how many are implemented to
> > demonstrate recursion (or to demonstrate the difference between
> > iteration and recursion)? :)

(I can't get to the parent directly, so I follow up indirectly.)

Factorials become an interesting demonstration of recursion when done
well. There's a paper by Richard J. Fateman, citing Peter Luschny:




Fateman's "major conclusion is that you should probably not use the
'naive' factorial programs for much of anything". I take this to
include their use as examples of recursion, unless the purpose is to
make the idea of recursion look bad.
-- 
http://mail.python.org/mailman/listinfo/python-list