Sending an email with a binary attachment

2016-02-29 Thread Anthony Papillion
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA512

Hello Everyone,

I've been trying to write a /very/ simple script that will email a
binary file to an email address when run. Pretty simple. I've done
quite a bit of research and have finally settled on the following code:

http://pastebin.com/sryj98wW

For some reason though, sending mail is failing every time. I've made
sure that the password is correct (which seems to be the most usual
error).

Still, I just can't get it to work. Can someone take a look at this
code and give me some advice?

Thanks!
Anthony
-BEGIN PGP SIGNATURE-

iQIcBAEBCgAGBQJW0/zYAAoJEAKK33RTsEsVH5YP/jisLkuK4SAD6E06dO/czn1V
bO1QlzqTje8giXUWGyVeGS9MHAA1S2TlHc/rp01/DHTt1iYT50qGIaPxzUxBTMEX
mBCFFUSgg6LjkY+9b0c+o4OmviZlX7/KA6wT9IpFEG0l86Uj+z39rcBHm+GauiX+
IgMS5lWXfPmIEwiKzByMduxEgfj6kQW6PhkR5hTmOvd3sbILR91U9NiigrUD1ukM
+eN4LnKVu5Qpyb8X34Ze0NF7tiMr7tTQyBIq6C6ORGR/IPri407Ro8ACHBd55xZV
QxHjFVemms9s7ala0aoBcpRKr4PG35Ebm+7CcZaDj0fdk11mRvpqCZtGfodw/+sL
Crrxoz11hC//DHslZrEuNlJHgRqnsw+abKG8jIaJCrIW1f9BiyiWse+RRwbpN8IY
1C0gD4E1N3dUqGFrhyD/Xuy0tkXWpfiYhcLJQY+j7exrf00s+ASUTrd92lDCzxW4
pwuPZYN6nXY6dh9q72fgoEzqU0eDIzSgX99fODcxqp1L2ieczWMMajlWQJrJEcUe
UgxB8IvlvuD3NpzZXisEG8ZzqhZT6GOurHGbBusAW2M9zaqImb4qGEid7HS4BL/c
Kj7PspXz+8gD3SKZ/dOBdFlKK1KM1utekB0UnmBboZ9nXVhz5qVPaiVgjPunB5TG
1fMuuGiy2yl5pfTNvH8a
=Ff+J
-END PGP SIGNATURE-

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


usage of try except for review.

2016-02-29 Thread Ganesh Pal
Iam on python 2.6 and Linux , need your suggestion on the usage of try
and except in this program and


Modified code:


#!/usr/bin/env python


"""

"""

import os

import shlex

import subprocess

import sys

import time

import logging

import run

import pdb



def run_cmd_and_verify(cmd, timeout=1000):

try:

out, err, ret = run(cmd, timeout=timeout)

assert ret ==0,"ERROR (ret %d): " \

" \nout: %s\nerr: %s\n" % (ret, out, err)

except Exception as e:

logging.error("Failed to run %s got %s" % (cmd, e))

return False

return True



def run_test():

"""

Mount

"""

pdb.set_trace()

for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]:

try:

if not run_cmd_and_verify(cmd, timeout=3600):

return False

except:

   logging.error("Failure while running command %")

logging.info("Setup and Creation Done !!!")



#

cmd = "run_scan"

out, err, ret = run(cmd)



for cmd in ["create_data.py -nfs ",

"validate.py -30 "]:

try:

if not run_cmd_and_verify(cmd, timeout=3600):

   return False

except:

logging.error("")

return False

logging.info("Mount IS START.Done !!!")



def main():

if not run_test():

sys.exit("Exiting Main")



if __name__ == '__main__':

main()



Question 1:



1. Have I used try and expect block correctly  ? , In my case I have
the except block that's  is not needed it just gives an  message I
have still included for the sake of try block


try:

if not run_cmd_and_verify(cmd, timeout=3600):

return False

except:

   logging.error("inside except")

return False




2.  If a failure’s are encountered  the error by assert condition the
errors are now displayed on the screen , how do I redirect it to log
file using logging error


def run_cmd_and_verify(cmd, timeout=1000):

try:

out, err, ret = run(cmd, timeout=timeout)

assert ret ==0,"ERROR (ret %d): " \

" \nout: %s\nerr: %s\n" % (ret, out, err)

except Exception as e:

logging.error("Failed to run %s got %s" % (cmd, e))

return False

return True



#script_10.py

Failed to run  mount /nfs got ERROR (ret 1):

out:
host-44-3 exited with status 1

err:
host-44-3: mount_efs:  on /nfs: efs is already mounted



3. my function def has 1000 but Iam using 3600 in the calling fnx etc
, Time out value are overwritten ?

4. Any further improvement particularly on try -except ?


Regards,
Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Chris Angelico
On Mon, Feb 29, 2016 at 6:20 PM, Rustom Mody  wrote:
> On Monday, February 29, 2016 at 11:48:25 AM UTC+5:30, Marko Rauhamaa wrote:
>> Gordon Levi :
>>
>> > Nobody likes filling in forms but how do you suggest converting a form
>> > based app into something loveable.
>>
>> Straight HTML does forms just fine without CSS or JavaScript, yet few
>> can resist.
>
> Abjure JS/CSS is a virtue? Why?
> In any case with or without its still a form not plain (printf/scanf) text.
> So what exactly are we talking of?

Abjuring JS may be a virtue (or at least, making it a non-critical
part of your web site), but CSS is important to document structure and
layout. The combination of HTML and CSS provides a logical structure
with separate styling, which IMO is an excellent thing. It's possible
to accomplish the same goal in other ways (for instance, Markdown
source code for the structure and HTML for the layout), but CSS
provides enough flexibility to do this just fine on its own.

Incidentally, HTML+CSS is another excellent example of code being used
to create a visual effect. While there *are* WYSIWYG HTML editors, I'm
not familiar with any WYISWYG HTML+CSS editors, and I much more often
see a fast-turnaround code editing system such as codepen.io - you
change the HTML in one box, or the CSS in another, and the result down
below changes in real-time. It wouldn't be too hard to create
something like this for a GUI, and it'd remove some of that feeling of
non-interactivity while still retaining all the benefits of code above
drag-and-drop.

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


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Marko Rauhamaa
Rustom Mody :

> On Monday, February 29, 2016 at 11:48:25 AM UTC+5:30, Marko Rauhamaa wrote:
>> Gordon Levi :
>> 
>> > Nobody likes filling in forms but how do you suggest converting a form
>> > based app into something loveable.
>> 
>> Straight HTML does forms just fine without CSS or JavaScript, yet few
>> can resist.
>
> Abjure JS/CSS is a virtue? Why?

I have used some minute amounts of CSS when I have wanted to pay
attention to the aesthetics (http://pacujo.net/esperanto/literaturo/juho/>).

However, then the point is conveying/exchanging info, straight HTML is
all that is needed: http://pacujo.net/esperanto/course/>.

As for why you should avoid JS/CSS, Web pages open very slowly, jump
around wildly during rendering and have unexpected artifacts (not to
mention the numerous data collection abuses) when they are encumbered
with truckloads of state-of-the-art web dev gimmicks.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


why not define a EVENT_ERROR in selectors module?

2016-02-29 Thread gansteed
as the title:

I'm reading the source code of selectors, I got this:

# generic events, that must be mapped to implementation-specific ones
EVENT_READ = (1 << 0)
EVENT_WRITE = (1 << 1)

maybe we can add definitions for EVENT_ERROR like this:

# Choose the best implementation, roughly:
#epoll|kqueue|devpoll > poll > select.
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
if 'KqueueSelector' in globals():
DefaultSelector = KqueueSelector
EVENT_ERROR = EVENT_WRITE << 1
elif 'EpollSelector' in globals():
...
elif ...:
...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Chris Angelico
On Mon, Feb 29, 2016 at 7:25 PM, Marko Rauhamaa  wrote:
> As for why you should avoid JS/CSS, Web pages open very slowly, jump
> around wildly during rendering and have unexpected artifacts (not to
> mention the numerous data collection abuses) when they are encumbered
> with truckloads of state-of-the-art web dev gimmicks.

And when I pick up a paintbrush, canvas, and oil paints, the result is
appallingly hard on the eyes. Clearly oil paints should not be used,
and we should just place the brush tastefully on the canvas, because
that is guaranteed to look good.

Don't blame the tool for its poor users.

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


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Marko Rauhamaa
Chris Angelico :

> CSS is important to document structure and layout.

Most Web pages had better not concern themselves with layout but with
info content only. Unfortunately, HTML is a dirt-poor language for
markup (no extensibility or programmability) so I can understand the
temptation to side-step it with CSS.

CSS has tons of esoterics but seems to lack some very basic facilities
so I can understand the temptation to side-step it with JavaScript.

> Incidentally, HTML+CSS is another excellent example of code being used
> to create a visual effect. While there *are* WYSIWYG HTML editors, I'm
> not familiar with any WYISWYG HTML+CSS editors, and I much more often
> see a fast-turnaround code editing system such as codepen.io - you
> change the HTML in one box, or the CSS in another, and the result down
> below changes in real-time. It wouldn't be too hard to create
> something like this for a GUI, and it'd remove some of that feeling of
> non-interactivity while still retaining all the benefits of code above
> drag-and-drop.

Yes, WYSIWYG is a doomed approach. There's a difference between input
and output.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Marko Rauhamaa
Chris Angelico :
> On Mon, Feb 29, 2016 at 7:25 PM, Marko Rauhamaa  wrote:
>> As for why you should avoid JS/CSS, Web pages open very slowly, jump
>> around wildly during rendering and have unexpected artifacts (not to
>> mention the numerous data collection abuses) when they are encumbered
>> with truckloads of state-of-the-art web dev gimmicks.
>
> And when I pick up a paintbrush, canvas, and oil paints, the result is
> appallingly hard on the eyes. Clearly oil paints should not be used,
> and we should just place the brush tastefully on the canvas, because
> that is guaranteed to look good.
>
> Don't blame the tool for its poor users.

In that vein...

   The men turned away and went toward Sodom, but Abraham remained
   standing before the Lord. Then Abraham approached him and said: “Will
   you sweep away the righteous with the wicked? What if there are fifty
   righteous people in the city? Will you really sweep it away and not
   spare the place for the sake of the fifty righteous people in it? Far
   be it from you to do such a thing—to kill the righteous with the
   wicked, treating the righteous and the wicked alike. Far be it from
   you! Will not the Judge of all the earth do right?”

   The Lord said, “If I find fifty righteous people in the city of
   Sodom, I will spare the whole place for their sake.”

   Then Abraham spoke up again: “Now that I have been so bold as to
   speak to the Lord, though I am nothing but dust and ashes, what if
   the number of the righteous is five less than fifty? Will you destroy
   the whole city for lack of five people?”

   “If I find forty-five there,” he said, “I will not destroy it.”

   Once again he spoke to him, “What if only forty are found there?”

   He said, “For the sake of forty, I will not do it.”

   Then he said, “May the Lord not be angry, but let me speak. What if
   only thirty can be found there?”

   He answered, “I will not do it if I find thirty there.”

   Abraham said, “Now that I have been so bold as to speak to the Lord,
   what if only twenty can be found there?”

   He said, “For the sake of twenty, I will not destroy it.”

   Then he said, “May the Lord not be angry, but let me speak just once
   more. What if only ten can be found there?”

   He answered, “For the sake of ten, I will not destroy it.”

   When the Lord had finished speaking with Abraham, he left, and
   Abraham returned home.

   https://www.biblegateway.com/passage/?search=Genesis%2018&versio
   n=NIV>

   Early the next morning Abraham got up and returned to the place where
   he had stood before the Lord. He looked down toward Sodom and
   Gomorrah, toward all the land of the plain, and he saw dense smoke
   rising from the land, like smoke from a furnace.

   https://www.biblegateway.com/passage/?search=Genesis%2019&versio
   n=NIV>


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
Iam really sorry , I will have to resend my question again , because
the earlier post had mistakes and formatting was bad , so apologies
for top posting  will try to avoid such mistakes in future.


Iam on python 2.6 and Linux , need your suggestion on the usage of try
and except in this program

#!/usr/bin/env python


"""
"""
import os
import shlex
import subprocess
import sys
import time
import logging
import run
import pdb

def run_cmd_and_verify(cmd, timeout=1000):

try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True

def run_test():
"""
Mount

"""
pdb.set_trace()

for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
   logging.error("Some meaningful message")
logging.info("Setup and Creation Done !!!")
#
cmd = "run_scan"
out, err, ret = run(cmd)

for cmd in ["create_data.py -nfs ",
"validate.py -30 "]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
   return False
except:
logging.error("some meaningful message")
return False
logging.info("Mount IS START.Done !!!")

def main():

if not run_test():
sys.exit("Exiting Main")

if __name__ == '__main__':
main()

Question 1:

(a)  Have I used try and expect block correctly  ?  in run_test()  I
have  expect  block which displays some error message  instead of pass
, is it fine ?

 (b)  Have I returned True and  False correctly , looks fine for me

try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
   logging.error("inside except")
   return False

Question 2.

(a) If a failure’s are encountered  the error by assert condition the
errors are now displayed on the screen , how do I redirect it to log
file using logging error
 because the moment assert ret==0 becomes true the program exits

def run_cmd_and_verify(cmd, timeout=1000):
try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \

" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True

#script_10.py
Failed to run  mount /nfs got ERROR (ret 1):
out:
host-44-3 exited with status 1
err:
host-44-3: mount_efs:  on /nfs: efs is already mounted

3. my function def has 1000 but Iam using 3600 in the calling fnx etc
, Time out value are overwritten ?
4. Any further improvement particularly on try -except ?


Regards,
Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread BartC

On 29/02/2016 00:49, Steven D'Aprano wrote:

On Mon, 29 Feb 2016 01:29 am, BartC wrote:


20 years ago, when these things were simpler, MS Word had a mind of its
own even then. I had to produce a manual of few hundred pages, with
diagrams and images, and it just wasn't going to happen. Not without
spending a year on it. And employing someone to do it cost thousands.


So you're saying that somebody else knew how to do it, but you didn't, so it
would take you a year?


An outsider would be using their own methods, perhaps some more apt DTP 
solution; I wouldn't know.



I find it hard to believe that Word 20 years ago couldn't deal with
something as small as a couple of hundred pages with diagrams.


Possibly, but just because it could, maybe it does so in a complicated 
manner. Or maybe it's wasn't flexible. Or maybe some things I needed 
just weren't possible.


(How did it do contents, appendices, indices, references to labelled 
items in the rest of the text? One manual I did was for the very script 
language I was using: how could Word render code, and do so with 
automatic highlighting (eg boldening) of keywords for a language it knew 
nothing about?)


And my experience is that a lot of these things were incredibly fiddly 
anyway. I'm really the sort of guy who needs to have separate plain-text 
and rendered verions of a document.



I find it
much easier to believe that you're the sort of guy who would rather spend
three days inventing your solution from scratch (involving your own custom
programming language no less) than three hours reading the manual of the
existing solution.


The language wasn't created just for this purpose. It was part of the 
application the manual was about. And in fact it had its own manual 
later on. The graphics application was also the one used to preview the 
rendered pages before sending them off to a Postscript printer.


(And actually some of the diagrams were in a 3D vector format belonging 
to the application, a projection of which could sent as vector graphics 
to PS; I would have needed to rasterise them for Word.


So in some ways, my solution was more sophisticated than using Word.)


In the end I spent a week or two throwing together some simple mark-up
language, written in my own editor, which was then processed by my own
script language and ending up (via my own graphics software along the
way) as Postscript. The results were perfect.


/s/three days/two weeks/


Actually I can't remember how long it took. I know I spent some time 
building font-data tables for the fonts which only existed inside the 
Postscript printer.



(Have you ever had a situation where you have to edit a bit of text
where a word is in italic or has some particular style. You delete the
word, and try and add some more text, but it persists in using the style
of the deleted text rather than the current style.



You know that Word lets you reset the style to plain (Roman) text? There's
no need to delete the entire line, let alone the entire document. Text
styles are toggled: just hit Ctrl-I (or is it Ctrl-Shift-I, it's been a
while since I've used Word) to toggle italic on and off. Even if the
current paragraph defaults to italic, you can still toggle it off that way.


Yes but you have to keep doing it. It's not just Word; even Thunderbird 
(which I'm using right now) sometimes gets in a twist about quoted text 
(shown in blue) and new text shown in black. It wouldn't matter but 
quoted text doesn't wrap at the ends of lines.


It also keeps screwing up any copy and paste that happens to have 
indents. Here's one example:


One
Two
Three

And if I do a simple copy and paste:

One
Two
Three

And it's not always as simple as just stripping leading spaces; 
sometimes they are just munged. And I haven't even posted yet which 
often gives yet more unexpected results.


Now someone is going to tell me what I'm doing wrong. I need to set X in 
Y to Z; obviously! The point is that it should Just Work. Multiply these 
little things by dozens of examples and you will see how using Other 
People's Software can often be a complete pain.




--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Correct IDLE usage (was Reason for not allowing import twice but allowing reload())

2016-02-29 Thread Rustom Mody
On Monday, February 29, 2016 at 12:10:28 PM UTC+5:30, alien2utoo wrote:
> Hello list,
> 
> We can not import a module twice in a session of Python (subsequent attempts 
> to import same module don't result in any error though, but it is 
> not-effective).
> 
> However after making change to module, we can reload() it (if not reload(), 
> we could possibly have reimport statement) to get the updates in module.
> 
> I am a newbie in Python (learning via IDLE) and trying to understand
>


Hi and welcome!
 

> - what is extra (special) that import does, that reload() doesn't?
> - if both do the same internally and externally, why subsequent imports of 
> same module are ineffective?
> - if subsequent imports of same module in a session are not effective, why 
> not simply flag those attempts as an error, rather than letting them go 
> effect-less.
> 
> Kindly help me understand the reasons behind.

I guess Ian and Chris have answered well enough in a general way.

However I wonder at a more pragmatic level: 

Is import needed at all when trying out in Idle?

[Maybe Idle experts can comment...]

In more detail:

1. Start idle
2. Open new with Ctrl-n

3. Put the following into foo.py
---
x = 3
def foo(y) : return x+y
---

4. Load it into python with F5 (or Run-> Run_Module) And have this interaction

>>>  RESTART 
>>> 
>>> x
3
>>> foo(2)
5

Note the restart

5. Switch back to foo.py and change the '+' to '*'; F5
>>>  RESTART 
>>> 
>>> foo(2)
6

SO THE CHANGE IS EFFECTED

6. Yes there is a difference between importing and 'F5-ing'; 
   To see that I add to bottom of foo.py

if __name__ == '__main__':
print "if"
else:
print "else"

7. Now with F5:
>>>  RESTART 
>>> 
if

 Whereas with import:

>>> import foo
else
>>> 

So it does appear that
1. import not necessary with(in) idle
2. However import and f5 (ie is run as main) are different

May some idle experts elaborate on this? Whats the idle idiom of import-ing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help

2016-02-29 Thread tomwilliamson115
Thanks. If a word appears more than once how would I bring back both locations? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread alien2utoo
Thanks Chris and Ian,

Your suggested experiments and explanations have really provided some good 
insights, something Tutorial didn't indicate.

Ian's explanation reminds me of 

#ifndef _HEADER_H_
#define _HEADER_H_
...
#endif  // _HEADER_H_

in C/C++, and I can draw parallels to why subsequent attempts to import same 
module shouldn't result in flagging an error, and need for multiple imports to 
refer to same information.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 7:53 AM,  wrote:

> Thanks. If a word appears more than once how would I bring back both
> locations?
>

This is not generally a free coding service.  Fortunately for you Tom,
Jacob was kind enough to do your homework for you.  The problem with doing
someone's homework for them is that they don't learn anything.  Why don't
you go line by line through his code and understand what he has written.  I
think if you do that you will see how to solve the problem of finding then
next match (if there is one)

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



-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread alien2utoo
Hello Rustom,

F5 in Idle restarts the Python interpreter (that's what my impression is). 
Whatever you have done earlier at Idle prompt (in Idle session) before F5 is 
gone after F5.

Try simple experiment at prompt.

>>> myvar="hello"
>>> myvar
'hello'

myvar is gone after F5.

As for need of import in Idle session, I use it to
- import sys
- sys.append.path('D:\\Where\\Ever\\My\\Modules\\Lie')
- import mymodule
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread alien2utoo
> As for need of import in Idle session, I use it to
> - import sys
> - sys.append.path('D:\\Where\\Ever\\My\\Modules\\Lie')

Kindly read above as
sys.path.append()

> - import mymodule

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


Re: Help

2016-02-29 Thread Mark Lawrence

On 29/02/2016 12:53, [email protected] wrote:

Thanks. If a word appears more than once how would I bring back both locations?



I've no idea without any context, would you please care to elucidate, 
thanks.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


General computer language, syntax question.

2016-02-29 Thread jonas . thornvall
I have a problem programming uniform networks, "x nodes with y links" that turn 
out to be really hairy to solve for me and i feel i really lack the programming 
features 

"Actually i program in javascript" but the problem seem general for all 
programming languages including Pyhton.

For a beautiful solution it would require "If in list/array return boolean" "If 
not in list/array return boolean". 

But there is no such feature Python nor Javascript, so instead i set boolean 
value "inlist" to false and loop thru, to see if it is already in list. If not 
it is added to list. 

So if the current node i generate links for is x and i try to generate a link 
to  node z, and z's links exhausted i will add it to exhausted list.

And if there is node-x exhausted entries in list, well then script should break 
because it will lock into a cycle. The cyclic lockup is due to only a subset of 
the networks on the form (links*deep)+1=nodes is possible.

So what i need is to know howto write "if list/array ***empty*** do {something}"

I sure know howto check if an array have 1 element 2,3,4 but how do you check 
for empty.

I think it is crazy that you can not do general comparissons of the type 
If in list/array
If not in list/array

But it is even more crazy that you can not check if list/array is empty, that 
is just madness.
-- 
https://mail.python.org/mailman/listinfo/python-list


Reason for not allowing import twice but allowing reload()

2016-02-29 Thread Rustom Mody
On Monday, February 29, 2016 at 6:53:09 PM UTC+5:30, [email protected] wrote:
> Hello Rustom,
> 
> F5 in Idle restarts the Python interpreter (that's what my impression is). 
> Whatever you have done earlier at Idle prompt (in Idle session) before F5 is 
> gone after F5.
> 
> Try simple experiment at prompt.
> 
> >>> myvar="hello"
> >>> myvar
> 'hello'
> 
> myvar is gone after F5.
> 
> As for need of import in Idle session, I use it to
> - import sys
> - sys.append.path('D:\\Where\\Ever\\My\\Modules\\Lie')
> - import mymodule

Why does one use (something like) idle?
To experiment.

So what's your experiment-focus?
If it is mymodule then mymodule should be open in idle file window and idle 
will take care of paths

If its someothermodule.py that has an import of mymodule.py then
someothermodule should be handling the paths issue.

In neither case I see a reason to do it at idle prompt

[At least that's my understanding, hope an idle expert will weigh in on this]

In linux this question does not typically arise as one starts idle from the 
shell in the same directory as the python files one wants to play with

In windows... not sure of idiom...
Maybe right-click the idle icon and change its 'start-in' to the path where
your python files are situated?

My general impression (best-practices not semantics) is that changing sys.path
is allowed but hackish.
1. Modify sys.path
2. Using PYTHONPATH env variable
3. Use relative imports
4. Use packages
?. .pth files

is roughly decreasing in hackishness though unfortunately increasing in 
sophistication

http://stackoverflow.com/questions/19917492/how-to-use-pythonpath
http://stackoverflow.com/questions/18521503/pydev-how-to-avoid-adding-sub-directories-to-python-path-in-order-to-fix-unres
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General computer language, syntax question.

2016-02-29 Thread jonas . thornvall
Den måndag 29 februari 2016 kl. 14:45:37 UTC+1 skrev [email protected]:
> I have a problem programming uniform networks, "x nodes with y links" that 
> turn out to be really hairy to solve for me and i feel i really lack the 
> programming features 
> 
> "Actually i program in javascript" but the problem seem general for all 
> programming languages including Pyhton.
> 
> For a beautiful solution it would require "If in list/array return boolean" 
> "If not in list/array return boolean". 
> 
> But there is no such feature Python nor Javascript, so instead i set boolean 
> value "inlist" to false and loop thru, to see if it is already in list. If 
> not it is added to list. 
> 
> So if the current node i generate links for is x and i try to generate a link 
> to  node z, and z's links exhausted i will add it to exhausted list.
> 
> And if there is node-x exhausted entries in list, well then script should 
> break because it will lock into a cycle. The cyclic lockup is due to only a 
> subset of the networks on the form (links*deep)+1=nodes is possible.
> 
> So what i need is to know howto write "if list/array ***empty*** do 
> {something}"
> 
> I sure know howto check if an array have 1 element 2,3,4 but how do you check 
> for empty.
> 
> I think it is crazy that you can not do general comparissons of the type 
> If in list/array
> If not in list/array
> 
> But it is even more crazy that you can not check if list/array is empty, that 
> is just madness.

I mean for for example Javascript
if (typeof array[index] !== 'undefined' && array[index] !== null) {
or this one
if (array[index] != null) {

I mean how do they come up with such convoluted syntax, do they pull it out of 
ass? Well one can always say it is needed because undefined not equal to null.

But would not if (array[index]==empty) suffice and be alot clearer?



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


Re: General computer language, syntax question.

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 8:45 AM,  wrote:

> I have a problem programming uniform networks, "x nodes with y links" that
> turn out to be really hairy to solve for me and i feel i really lack the
> programming features
>
> "Actually i program in javascript" but the problem seem general for all
> programming languages including Pyhton.
>
> For a beautiful solution it would require "If in list/array return
> boolean" "If not in list/array return boolean".
>
> But there is no such feature Python nor Javascript, so instead i set
> boolean value "inlist" to false and loop thru, to see if it is already in
> list. If not it is added to list.
>
> So if the current node i generate links for is x and i try to generate a
> link to  node z, and z's links exhausted i will add it to exhausted list.
>
> And if there is node-x exhausted entries in list, well then script should
> break because it will lock into a cycle. The cyclic lockup is due to only a
> subset of the networks on the form (links*deep)+1=nodes is possible.
>
> So what i need is to know howto write "if list/array ***empty*** do
> {something}"
>
> I sure know howto check if an array have 1 element 2,3,4 but how do you
> check for empty.
>
> I think it is crazy that you can not do general comparissons of the type
> If in list/array
> If not in list/array
>
> But it is even more crazy that you can not check if list/array is empty,
> that is just madness.
> --
> https://mail.python.org/mailman/listinfo/python-list
>

>>> l = [1,2,3,4]
>>> if 1 in l:
...   print 1
...
1
>>> if 6 in l:
...   print 1
...
>>>
>>> l = []
>>> if len(l) == 0:
...   print 'empty'
...
empty


-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General computer language, syntax question.

2016-02-29 Thread MRAB

On 2016-02-29 13:45, [email protected] wrote:

I have a problem programming uniform networks, "x nodes with y links" that turn 
out to be really hairy to solve for me and i feel i really lack the programming features

"Actually i program in javascript" but the problem seem general for all 
programming languages including Pyhton.

For a beautiful solution it would require "If in list/array return boolean" "If not 
in list/array return boolean".

But there is no such feature Python nor Javascript, so instead i set boolean value 
"inlist" to false and loop thru, to see if it is already in list. If not it is 
added to list.

So if the current node i generate links for is x and i try to generate a link 
to  node z, and z's links exhausted i will add it to exhausted list.

And if there is node-x exhausted entries in list, well then script should break 
because it will lock into a cycle. The cyclic lockup is due to only a subset of 
the networks on the form (links*deep)+1=nodes is possible.

So what i need is to know howto write "if list/array ***empty*** do {something}"

I sure know howto check if an array have 1 element 2,3,4 but how do you check 
for empty.

I think it is crazy that you can not do general comparissons of the type
If in list/array
If not in list/array

But it is even more crazy that you can not check if list/array is empty, that 
is just madness.


Does this help?

>>> items = ['a', 'b', 'c', 'd', 'e']
>>> 'c' in items
True
>>> 'f' in items
False
>>> len(items)
5
>>> len([])
0

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


Re: General computer language, syntax question.

2016-02-29 Thread jonas . thornvall
Den måndag 29 februari 2016 kl. 14:57:04 UTC+1 skrev [email protected]:
> Den måndag 29 februari 2016 kl. 14:45:37 UTC+1 skrev [email protected]:
> > I have a problem programming uniform networks, "x nodes with y links" that 
> > turn out to be really hairy to solve for me and i feel i really lack the 
> > programming features 
> > 
> > "Actually i program in javascript" but the problem seem general for all 
> > programming languages including Pyhton.
> > 
> > For a beautiful solution it would require "If in list/array return boolean" 
> > "If not in list/array return boolean". 
> > 
> > But there is no such feature Python nor Javascript, so instead i set 
> > boolean value "inlist" to false and loop thru, to see if it is already in 
> > list. If not it is added to list. 
> > 
> > So if the current node i generate links for is x and i try to generate a 
> > link to  node z, and z's links exhausted i will add it to exhausted list.
> > 
> > And if there is node-x exhausted entries in list, well then script should 
> > break because it will lock into a cycle. The cyclic lockup is due to only a 
> > subset of the networks on the form (links*deep)+1=nodes is possible.
> > 
> > So what i need is to know howto write "if list/array ***empty*** do 
> > {something}"
> > 
> > I sure know howto check if an array have 1 element 2,3,4 but how do you 
> > check for empty.
> > 
> > I think it is crazy that you can not do general comparissons of the type 
> > If in list/array
> > If not in list/array
> > 
> > But it is even more crazy that you can not check if list/array is empty, 
> > that is just madness.
> 
> I mean for for example Javascript
> if (typeof array[index] !== 'undefined' && array[index] !== null) {
> or this one
> if (array[index] != null) {
> 
> I mean how do they come up with such convoluted syntax, do they pull it out 
> of ass? Well one can always say it is needed because undefined not equal to 
> null.
> 
> But would not if (array[index]==empty) suffice and be alot clearer?

Sorry but would not if (array==empty) suffice and be alot clearer?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General computer language, syntax question.

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 9:05 AM,  wrote:

> Den måndag 29 februari 2016 kl. 14:57:04 UTC+1 skrev [email protected]:
> > Den måndag 29 februari 2016 kl. 14:45:37 UTC+1 skrev
> [email protected]:
> > > I have a problem programming uniform networks, "x nodes with y links"
> that turn out to be really hairy to solve for me and i feel i really lack
> the programming features
> > >
> > > "Actually i program in javascript" but the problem seem general for
> all programming languages including Pyhton.
> > >
> > > For a beautiful solution it would require "If in list/array return
> boolean" "If not in list/array return boolean".
> > >
> > > But there is no such feature Python nor Javascript, so instead i set
> boolean value "inlist" to false and loop thru, to see if it is already in
> list. If not it is added to list.
> > >
> > > So if the current node i generate links for is x and i try to generate
> a link to  node z, and z's links exhausted i will add it to exhausted list.
> > >
> > > And if there is node-x exhausted entries in list, well then script
> should break because it will lock into a cycle. The cyclic lockup is due to
> only a subset of the networks on the form (links*deep)+1=nodes is possible.
> > >
> > > So what i need is to know howto write "if list/array ***empty*** do
> {something}"
> > >
> > > I sure know howto check if an array have 1 element 2,3,4 but how do
> you check for empty.
> > >
> > > I think it is crazy that you can not do general comparissons of the
> type
> > > If in list/array
> > > If not in list/array
> > >
> > > But it is even more crazy that you can not check if list/array is
> empty, that is just madness.
> >
> > I mean for for example Javascript
> > if (typeof array[index] !== 'undefined' && array[index] !== null) {
> > or this one
> > if (array[index] != null) {
> >
> > I mean how do they come up with such convoluted syntax, do they pull it
> out of ass? Well one can always say it is needed because undefined not
> equal to null.
> >
> > But would not if (array[index]==empty) suffice and be alot clearer?
>
> Sorry but would not if (array==empty) suffice and be alot clearer?
> --
> https://mail.python.org/mailman/listinfo/python-list
>

You might have better luck on a javascript mailing list.  Not sure crazy,
madness, ass are descriptive to your problems

-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General computer language, syntax question.

2016-02-29 Thread Mark Lawrence

On 29/02/2016 13:45, [email protected] wrote:

I have a problem programming uniform networks, "x nodes with y links" that turn 
out to be really hairy to solve for me and i feel i really lack the programming features

"Actually i program in javascript" but the problem seem general for all 
programming languages including Pyhton.

For a beautiful solution it would require "If in list/array return boolean" "If not 
in list/array return boolean".

But there is no such feature Python nor Javascript, so instead i set boolean value 
"inlist" to false and loop thru, to see if it is already in list. If not it is 
added to list.

So if the current node i generate links for is x and i try to generate a link 
to  node z, and z's links exhausted i will add it to exhausted list.

And if there is node-x exhausted entries in list, well then script should break 
because it will lock into a cycle. The cyclic lockup is due to only a subset of 
the networks on the form (links*deep)+1=nodes is possible.

So what i need is to know howto write "if list/array ***empty*** do {something}"

I sure know howto check if an array have 1 element 2,3,4 but how do you check 
for empty.

I think it is crazy that you can not do general comparissons of the type
If in list/array
If not in list/array

But it is even more crazy that you can not check if list/array is empty, that 
is just madness.



Please see 
https://docs.python.org/3/library/stdtypes.html#truth-value-testing


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: General computer language, syntax question.

2016-02-29 Thread Ian Kelly
On Feb 29, 2016 7:11 AM,  wrote:
>
> Sorry but would not if (array==empty) suffice and be alot clearer?

In Python, you can just do "if len(array) == 0" or "if not array".

In JavaScript you have "if (array.length === 0)". Is there some problem
with that?

I would prefer this over your suggestion since it doesn't require some
variable named "empty" to have a sensible value set.

On the container test, as others pointed out, Python has the "in" operator.
JavaScript has a draft Array.prototype.includes method, but it doesn't have
broad cross-browser support yet.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General computer language, syntax question.

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 9:39 AM, Mark Lawrence 
wrote:

> On 29/02/2016 13:45, [email protected] wrote:
>
>> I have a problem programming uniform networks, "x nodes with y links"
>> that turn out to be really hairy to solve for me and i feel i really lack
>> the programming features
>>
>> "Actually i program in javascript" but the problem seem general for all
>> programming languages including Pyhton.
>>
>> For a beautiful solution it would require "If in list/array return
>> boolean" "If not in list/array return boolean".
>>
>> But there is no such feature Python nor Javascript, so instead i set
>> boolean value "inlist" to false and loop thru, to see if it is already in
>> list. If not it is added to list.
>>
>> So if the current node i generate links for is x and i try to generate a
>> link to  node z, and z's links exhausted i will add it to exhausted list.
>>
>> And if there is node-x exhausted entries in list, well then script should
>> break because it will lock into a cycle. The cyclic lockup is due to only a
>> subset of the networks on the form (links*deep)+1=nodes is possible.
>>
>> So what i need is to know howto write "if list/array ***empty*** do
>> {something}"
>>
>> I sure know howto check if an array have 1 element 2,3,4 but how do you
>> check for empty.
>>
>> I think it is crazy that you can not do general comparissons of the type
>> If in list/array
>> If not in list/array
>>
>> But it is even more crazy that you can not check if list/array is empty,
>> that is just madness.
>>
>>
> Please see
> https://docs.python.org/3/library/stdtypes.html#truth-value-testing
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>>> l = []
>>> l
[]
>>> if l:
...   print 'not empty'
...
>>>


-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread alien2utoo
> Why does one use (something like) idle?
> To experiment.
> 
> So what's your experiment-focus?

True. Experiment only.
What happens (and in environment) when you use
- import module
- from module import name
- from module import name as othername

Idle is start point, but we aren't always going to be Idle-ing, so need to work 
towards that as well while practicing basic concepts.

[P.S.- I think we are digressing a lot from original thread question.]
-- 
https://mail.python.org/mailman/listinfo/python-list


common mistakes in this simple program

2016-02-29 Thread Ganesh Pal
Iam on python 2.6 , need inputs on the common mistakes in this program
, may be you suggest what need to be improved from

1. usage of try- expect
2. Return of True/ False
3. Other improvement

#!/usr/bin/env python

"""
"""

import os
import shlex
import subprocess
import sys
import time
import logging
import run
import pdb


def run_cmd_and_verify(cmd, timeout=1000):
try:
pdb.set_trace()
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
print("Failed to run %s got %s" % (cmd, e))
return False
return True

def prep_host():
"""
Prepare clustering
"""
for cmd in ["ls -al",
"touch /tmp/file1",
"mkdir /tmp/dir1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
  print("Error: While preparing cluster !!!")
  return False
print("Preparing Cluster.Done !!!")
return True


def main():
functions = [prep_host]
for func in functions:
try:
func()
except Exception as e:
print(e)
return False
if __name__ == '__main__':
main()


Regards,
Gpal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread BartC

On 29/02/2016 07:11, Chris Angelico wrote:

On Mon, Feb 29, 2016 at 6:02 PM, Ian Kelly  wrote:

- if subsequent imports of same module in a session are not effective, why not 
simply flag those attempts as an error, rather than letting them go effect-less.


Because there are legitimate reasons for importing the same module
multiple times. For example, I have a script that imports the sys
module. It also imports the os module, which imports the sys module.
Both the main module of my script and the os module have need of the
sys module, so they both import it. If subsequent imports of the
module raised an exception, this wouldn't be possible.


I think the OP's talking more about the situation of having an active
session (IDLE was mentioned), importing a local module (a .py file
from the current directory), then editing the file and re-importing,
which has no effect. While I am sympathetic to the problem, I don't
believe the language should be changed here; what might be useful is
something that notices that an already-loaded module is now out of
date, but really, the best solution is a change of workflow that no
longer has long-running modules loading live-updated code.


Not in Python (this was pre-Python actually) but I once used such a 
technique all the time.


The main set of modules would be running a GUI application which also 
had a command line.


Some commands included editing, compiling [a discrete step] and running 
modules of the application that were under development. Then you had a 
very fast edit-run cycle for those modules without having to restart the 
entire application, and possibly reload the graphical data that was 
under test (which could be large), or having to do any other set-ups 
required for the test.


(Another reason in those days was that not all modules would fit into 
memory at once and a module could be unloaded once it had finished (in 
Python terms, running off the end of the module) to make room for another.)


What I'm saying is, you shouldn't dismiss something just because you 
can't think of enough uses for it.


--
Bartc

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


Dynamic object attribute creation

2016-02-29 Thread ast

Hello

Object's attributes can be created dynamically, ie

class MyClass:
   pass

obj = MyClass()
obj.test = 'foo'

but why doesn't it work with built-in classes int, float, list ?

L = [1, 8, 0]
L.test = 'its a list !'

(however lists are mutable, int, float ... are not)

Traceback (most recent call last):
 File "", line 1, in 
   L.test = 'its a list !'
AttributeError: 'list' object has no attribute 'test'

but it works on functions:

def funct(a,b):
print(a+b)

funct.test = 'this is a function'

funct.test
'this is a function'

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


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Grant Edwards
On 2016-02-29, Chris Angelico  wrote:

> Abjuring JS may be a virtue (or at least, making it a non-critical
> part of your web site),

Except the marketing people who decide on the requirements will never,
ever settle for what you can do with plain HTML/CSS.

In my experience, HTML/CSS makes a pretty awful GUI for a non-trivial
application.  With some Javascript and sweat, you can almost make it
to mediocre.

> but CSS is important to document structure and layout. The
> combination of HTML and CSS provides a logical structure with
> separate styling, which IMO is an excellent thing.

Indeed.  Separating the visual appearnce stuff from the "structure"
makes it a lot easier to deal with both, and the result is a lot more
robust as well.

-- 
Grant Edwards   grant.b.edwardsYow! The Korean War must
  at   have been fun.
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


EuroPython 2016: Regular ticket prices

2016-02-29 Thread M.-A. Lemburg
We will be switching to regular ticket prices very soon now:

 * Student:  EUR 120.00 (only available for students)
 * Personal: EUR 360.00 (for people enjoying Python from home)
 * Business: EUR 580.00 (for people using Python to make a living)

but still have a few early-bird tickets left.

If you buy until tomorrow at midnight (Tuesday, March 1st, 23:59 CET),
you can save up to EUR 200 on early-bird prices, compared to the above
regular prices:

  *** https://ep2016.europython.eu/en/registration/ ***

 More Information and Ticket Shop

PS: Please remember to submit your proposals for the conference. There
are only a few days left for submission. The deadline is Sunday, March 6:

  https://ep2016.europython.eu/en/call-for-proposals/


With gravitational regards,
--
EuroPython 2016 Team
http://ep2016.europython.eu/
http://www.europython-society.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help

2016-02-29 Thread Grant Edwards
On 2016-02-29, Joel Goldstick  wrote:
> On Mon, Feb 29, 2016 at 7:53 AM,  wrote:
>
>> Thanks. If a word appears more than once how would I bring back both
>> locations?
>
> This is not generally a free coding service.  Fortunately for you Tom,
> Jacob was kind enough to do your homework for you.  The problem with doing
> someone's homework for them is that they don't learn anything.

And thus don't compete for the good jobs with us who did learn things.

At least in theory.  

In real life they often still graduate and get hired anyway, get put
in the cubicle next to you, and you spend half your time cleaning up
after them.

-- 
Grant Edwards   grant.b.edwardsYow! NEWARK has been
  at   REZONED!!  DES MOINES has
  gmail.combeen REZONED!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 2:33 AM, BartC  wrote:
>> I think the OP's talking more about the situation of having an active
>> session (IDLE was mentioned), importing a local module (a .py file
>> from the current directory), then editing the file and re-importing,
>> which has no effect. While I am sympathetic to the problem, I don't
>> believe the language should be changed here; what might be useful is
>> something that notices that an already-loaded module is now out of
>> date, but really, the best solution is a change of workflow that no
>> longer has long-running modules loading live-updated code.
>
>
> Not in Python (this was pre-Python actually) but I once used such a
> technique all the time.
>
> The main set of modules would be running a GUI application which also had a
> command line.

I use this technique all the time, in current code. But not in Python.
The main reason is to have a server that permits clients to connect
and remain connected, and to update code in ways that affect those
connected clients. So by definition, I can't restart the server (it
would drop the connections), and the critical main loop doesn't
reload, but all the rest of the code does. It's pretty much the same
style you had.

Doing the same thing in Python would probably best be done using
"exec" rather than "import". It'd work, but you'd have to
differentiate in code between "load this module which can be reloaded"
and "import this module from the standard library" (where the latter
would be the regular "import" statement).

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


Re: Dynamic object attribute creation

2016-02-29 Thread Random832
On Mon, Feb 29, 2016, at 10:36, ast wrote:
> but why doesn't it work with built-in classes int, float, list ?
> 
> L = [1, 8, 0]
> L.test = 'its a list !'
> 
> (however lists are mutable, int, float ... are not)

Because those classes do not have attribute dictionaries, in order to
save space.

You can make a class without an attribute dictionary, by using
__slots__.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 2:43 AM, Grant Edwards  wrote:
> On 2016-02-29, Chris Angelico  wrote:
>
>> Abjuring JS may be a virtue (or at least, making it a non-critical
>> part of your web site),
>
> Except the marketing people who decide on the requirements will never,
> ever settle for what you can do with plain HTML/CSS.
>
> In my experience, HTML/CSS makes a pretty awful GUI for a non-trivial
> application.  With some Javascript and sweat, you can almost make it
> to mediocre.

That's why I said "may be". A pure CGI web site is pretty annoying
unless it's really brilliantly done. However, I prefer to see JS
restricted to actual interaction, instead of making it critical to the
basic layout. A lot of web sites these days load nothing but a script
that goes and loads everything else, while you gaze at a splash
screen. IMO that's unideal.

However, even that is probably a losing battle. :(

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


Xn project v002 is released

2016-02-29 Thread wij
Xn project tries to develop a more uniform language that can be used in
almost anywhere. It can be used for general files (e.g. executables),
general communication language, or even for an alive program that can grow.

Xn project is licensed as Public Domain (Historical Fact Principle). 
Anyone can start anything from Xn, as long as the historical fact is
maintained. Suggestions are also welcome.
https://sourceforge.net/projects/systemnode/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal  wrote:
> Iam on python 2.6

Python 2.6 has been unsupported since October 2013. Among other
things, that means it is no longer receiving security updates like
more recent versions. Unless you have an extremely strong reason for
wanting to stay to Python 2.6, you should update your Python version.

> 1. usage of try- expect

try-except in every single function is a code smell. You should only
be using it where you're actually going to handle the exception. If
you catch an exception just to log it, you generally should also
reraise it so that something further up the call chain has the
opportunity to handle it.

> 2. Return of True/ False

If you're returning True to mean "This completed without exception"
and False to mean "This raised an exception", then the more Pythonic
thing to do would just be to let the exception propagate, giving the
caller the opportunity to catch, inspect, and handle the exception.

> """
> """

An empty docstring is pointless.

> import os
> import shlex
> import subprocess
> import sys
> import time
> import logging
> import run
> import pdb

Most of these are unused. Only import modules that your code is actually using.

> def run_cmd_and_verify(cmd, timeout=1000):
> try:
> pdb.set_trace()
> out, err, ret = run(cmd, timeout=timeout)

What is "run"? It's imported like a module above, but here you're
using it like a function.

> assert ret ==0,"ERROR (ret %d): " \
> " \nout: %s\nerr: %s\n" % (ret, out, err)
> except Exception as e:
> print("Failed to run %s got %s" % (cmd, e))
> return False
> return True
>
> def prep_host():
> """
> Prepare clustering
> """
> for cmd in ["ls -al",
> "touch /tmp/file1",
> "mkdir /tmp/dir1"]:
> try:
> if not run_cmd_and_verify(cmd, timeout=3600):
> return False
> except:

What exceptions are you expecting this to catch? run_cmd_and_verify
already catches any expected exceptions that it raises.

Also, you should almost never use a bare except like this. Use "except
Exception" instead. A bare except will catch things like
KeyboardInterrupt and SystemExit that should not be caught.

>   print("Error: While preparing cluster !!!")
>   return False
> print("Preparing Cluster.Done !!!")
> return True
>
>
> def main():
> functions = [prep_host]
> for func in functions:
> try:
> func()
> except Exception as e:

As above, what exceptions are you expecting here?

> print(e)
> return False
> if __name__ == '__main__':
> main()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Larry Martell
On Sat, Feb 27, 2016 at 4:37 AM, Steven D'Aprano  wrote:
> The author of Requests, Kenneth Reitz, discusses his recent recovery from a
> MentalHealthError exception.
>
> http://www.kennethreitz.org/essays/mentalhealtherror-an-exception-occurred
>
> Although the connection to Python is only quite slim, I found it fascinating
> to read.

I found this to be a very sad story. Sure, he had some issues, but I
don't think they needed to drug him, and take all that he had learned
away from him and turn him back into what he was before.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dynamic object attribute creation

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 9:06 AM, Random832  wrote:
> On Mon, Feb 29, 2016, at 10:36, ast wrote:
>> but why doesn't it work with built-in classes int, float, list ?
>>
>> L = [1, 8, 0]
>> L.test = 'its a list !'
>>
>> (however lists are mutable, int, float ... are not)
>
> Because those classes do not have attribute dictionaries, in order to
> save space.
>
> You can make a class without an attribute dictionary, by using
> __slots__.

You can also make a list that does have an attribute dictionary by
subclassing it.

>>> class MyList(list): pass
...
>>> obj = MyList()
>>> obj.test = 'foo'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
> On Sat, Feb 27, 2016 at 4:37 AM, Steven D'Aprano  wrote:
>> The author of Requests, Kenneth Reitz, discusses his recent recovery from a
>> MentalHealthError exception.
>>
>> http://www.kennethreitz.org/essays/mentalhealtherror-an-exception-occurred
>>
>> Although the connection to Python is only quite slim, I found it fascinating
>> to read.
>
> I found this to be a very sad story. Sure, he had some issues, but I
> don't think they needed to drug him, and take all that he had learned
> away from him and turn him back into what he was before.

"All that he had learned" meaning his delusions and psychoses?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Ben Finney
Ian Kelly  writes:

> On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  
> wrote:
> > I found this to be a very sad story. Sure, he had some issues, but I
> > don't think they needed to drug him, and take all that he had
> > learned away from him and turn him back into what he was before.
>
> "All that he had learned" meaning his delusions and psychoses?

Indeed. If a revelation is unconnected to reality, it's misleading to
say that one has “learned” it.

Also, I don't see how anyone “took away” those experiences. He wrote an
article describing them and clearly still retains those experiences as
memories to recall as he wishes.

When someone describes the ill effects their mental illness produced, I
find it rather condescending for an observer to express regret that
the person no longer experiences those ill effects.

-- 
 \   “We have clumsy, sputtering, inefficient brains…. It is a |
  `\ *struggle* to be rational and objective, and failures are not |
_o__) evidence for an alternative reality.” —Paul Z. Myers, 2010-10-14 |
Ben Finney

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


Re: Sending an email with a binary attachment

2016-02-29 Thread Peter Pearson
On Mon, 29 Feb 2016 02:10:00 -0600, Anthony Papillion wrote:
[snip]
>
> http://pastebin.com/sryj98wW

To improve odds of your getting a response, let's get the code
into this thread.  Here it is, minus the #! preamble:

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import sys

FILE_TO_SEND = "/home/anthony/Desktop/passwords.kdb"

message = MIMEMultipart()
message['Subject'] = 'Password database update'
message['From'] = 'Database Update Script  For some reason though, sending mail is failing every time. I've made
> sure that the password is correct (which seems to be the most usual
> error).
>
> Still, I just can't get it to work. Can someone take a look at this
> code and give me some advice?

What exactly do you mean by "failing"?  If there's an error message,
show it.  If an exception is being generated, at least print some
information about the exception.


-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Rustom Mody
On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:
> Ian Kelly  writes:
> 
> > On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
> > > I found this to be a very sad story. Sure, he had some issues, but I
> > > don't think they needed to drug him, and take all that he had
> > > learned away from him and turn him back into what he was before.
> >
> > "All that he had learned" meaning his delusions and psychoses?
> 
> Indeed. If a revelation is unconnected to reality, it's misleading to
> say that one has "learned" it.

And who is the last arbiter on that 'reality'?

Niels Bohr random quote:
If anybody says he can think about quantum physics without getting giddy, that
only shows he has not understood the first thing about them.

Some more such: http://www.brainyquote.com/quotes/authors/n/niels_bohr.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sending an email with a binary attachment

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson  wrote:
> try:
> smtp.sendmail(message['From'],
> message['To'],
> message.as_string())
> except:
> print "Message sending has failed"
> sys.exit(1)
> print "Message sending was successful"
> sys.exit(0)
>

This is the problem, right here. Replace this code with:

smtp.sendmail(message['From'],
message['To'],
message.as_string())

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


Re: Error in Tree Structure

2016-02-29 Thread subhabangalore
On Saturday, February 27, 2016 at 9:43:56 PM UTC+5:30, Rustom Mody wrote:
> On Saturday, February 27, 2016 at 2:47:53 PM UTC+5:30, [email protected] 
> wrote:
> > I was trying to implement the code, 
> > 
> > import nltk
> > import nltk.tag, nltk.chunk, itertools
> > def ieertree2conlltags(tree, tag=nltk.tag.pos_tag):
> > words, ents = zip(*tree.pos())
> > iobs = []
> > prev = None
> > for ent in ents:
> > if ent == tree.node:
> > iobs.append('O')
> > prev = None
> > elif prev == ent:
> >  iobs.append('I-%s' % ent)
> > else:
> >  iobs.append('B-%s' % ent)
> >  prev = ent
> > words, tags = zip(*tag(words))
> > return itertools.izip(words, tags, iobs)
> > 
> > def ieer_chunked_sents(tag=nltk.tag.pos_tag):
> > for doc in ieer.parsed_docs():
> > tagged = ieertree2conlltags(doc.text, tag)
> > yield nltk.chunk.conlltags2tree(tagged)
> > 
> > 
> > from chunkers import ieer_chunked_sents, ClassifierChunker
> > from nltk.corpus import treebank_chunk
> > ieer_chunks = list(ieer_chunked_sents())
> > chunker = ClassifierChunker(ieer_chunks[:80])
> > print chunker.parse(treebank_chunk.tagged_sents()[0])
> > score = chunker.evaluate(ieer_chunks[80:])
> > print score.accuracy()
> > 
> > It is running fine. 
> > But as I am trying to rewrite the code as,
> > chunker = ClassifierChunker(list1),
> > where list1 is same value as,
> > ieer_chunks[:80]
> > only I am pasting the value as 
> > [Tree('S', [Tree('LOCATION', [(u'NAIROBI', 'NNP')]), (u',', ','), 
> > Tree('LOCATION', [(u'Kenya', 'NNP')]), (u'(', '('), Tree('ORGANIZATION', 
> > [(u'AP', 'NNP')]), (u')', ')'), (u'_', 'NNP'), Tree('CARDINAL', 
> > [(u'Thousands', 'NNP')]), (u'of', 'IN'), (u'laborers,', 'JJ'), 
> > (u'students', 'NNS'), (u'and', 'CC'), (u'opposition', 'NN'), 
> > (u'politicians', 'NNS'), (u'on', 'IN'), Tree('DATE', [(u'Saturday', 
> > 'NNP')]), (u'protested', 'VBD'), (u'tax', 'NN'), (u'hikes', 'NNS'), 
> > (u'imposed', 'VBN'), (u'by', 'IN'), (u'their', 'PRP$'), (u'cash-strapped', 
> > 'JJ'), (u'government,', 'NN'), (u'which', 'WDT'), (u'they', 'PRP'), 
> > (u'accused', 'VBD'), (u'of', 'IN'), (u'failing', 'VBG'), (u'to', 'TO'), 
> > (u'provide', 'VB'), (u'basic', 'JJ'), (u'services.', 
> > 'NN'),(u'(cm-kjd)', 'NN')])]
> > the value of whole list directly I am getting syntax error.
> 
> Dunno how literally you intend this but there is a "" near the end 
> of the list. Intended?

It is intended. As actual list was large.
And most likely I could solve the problem,
with 
from nltk.tree import Tree
I missed in my code.

Thank you for your kind time and discussion.

Regards,
RP
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Ganesh Pal
On Mon, Feb 29, 2016 at 9:59 PM, Ian Kelly  wrote:
> On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal  wrote:
>> Iam on python 2.6

>> 1. usage of try- expect
>
> try-except in every single function is a code smell. You should only
> be using it where you're actually going to handle the exception. If
> you catch an exception just to log it, you generally should also
> reraise it so that something further up the call chain has the
> opportunity to handle it.

How do we reraise the exception in python ,  I have used raise not
sure how to reraise the exception

>
>> def run_cmd_and_verify(cmd, timeout=1000):
>> try:
>> pdb.set_trace()
>> out, err, ret = run(cmd, timeout=timeout)
>
> What is "run"? It's imported like a module above, but here you're
> using it like a function.

Sorry run is a function  which was imported from a library , the
function had to be  # from utility import run ,

>> assert ret ==0,"ERROR (ret %d): " \
>> " \nout: %s\nerr: %s\n" % (ret, out, err)
>> except Exception as e:
>> print("Failed to run %s got %s" % (cmd, e))
>> return False
>> return True
>>
>> def prep_host():
>> """
>> Prepare clustering
>> """
>> for cmd in ["ls -al",
>> "touch /tmp/file1",
>> "mkdir /tmp/dir1"]:
>> try:
>> if not run_cmd_and_verify(cmd, timeout=3600):
>> return False
>> except:
>
> What exceptions are you expecting this to catch? run_cmd_and_verify
> already catches any expected exceptions that it raises.

This is a wrapper for Popen it runs the command and returns stdout
,stderror and returncode .The only exception it can return is a time
out exception

Here is the modified buggy code ,  Can I have Try and except with Pass
, how do I modify the  try and expect in the pre-host ?

#!/usr/bin/env python

"""
bugging code
"""
import logging
from utility import run

def run_cmd_and_verify(cmd, timeout=1000):
try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True

def prep_host():
"""
Prepare clustering
"""
for cmd in ["ls -al",
"touch /tmp/file1",
"mkdir /tmp/dir1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
logging.info("Preparing cluster failed ...")
return False
except:
pass
logging.info("Preparing Cluster.Done !!!")
return True


def main():
functions = [prep_host]
for func in functions:
try:
func()
except Exception as e:
logging.info(e)
return False
if __name__ == '__main__':
main()


Regards,
Gpal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Ben Finney
Rustom Mody  writes:

> On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:
> > Ian Kelly  writes:
> > 
> > > On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
> > > > I found this to be a very sad story. Sure, he had some issues, but I
> > > > don't think they needed to drug him, and take all that he had
> > > > learned away from him and turn him back into what he was before.
> > >
> > > "All that he had learned" meaning his delusions and psychoses?
> > 
> > Indeed. If a revelation is unconnected to reality, it's misleading to
> > say that one has "learned" it.
>
> And who is the last arbiter on that 'reality'?

A nice academic question. Not appropriate when we're discussing a real
person's psychotic episodes. Neither you nor I are experts in whether an
experience is psychosis, and the person already has an expert diagnosis.

So please don't de-rail into the weeds of second-guessing an expert in
mental health. Unless you know the person's mental health better than
their doctor (and you do not), don't second-guess the diagnosis they
received.

-- 
 \  “When [science] permits us to see the far side of some new |
  `\  horizon, we remember those who prepared the way – seeing for |
_o__)  them also.” —Carl Sagan, _Cosmos_, 1980 |
Ben Finney

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


Problem in creating list of lists

2016-02-29 Thread subhabangalore
I have few sentences, like, 

the film was nice.  
leonardo is great. 
it was academy award.

Now I want them to be tagged with some standards which may look like,

the DT film NN was AV nice ADJ
leonardo NN is AV great ADJ
it PRP was AV academy NN award NN

I could do it but my goal is to see it as,
[[('the','DT'),('film', 
'NN'),('was','AV'),('nice','ADJ')],[('leonardo','NN'),('is','AV'),('great','ADJ')],[('it','PRP'),
('was','AV'),('academy','NN'),('award','NN')]]

that is a list of lists where in each list there is a set of tuples. 
I could solve each one like I am getting 
one list with tuples, but not all within one.
As it is PoS Tagging so I am not being able to use zip.
If any one may please suggest. 

If any one may kindly suggest a solution.
Thanks in advance.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
On Mon, Feb 29, 2016 at 10:10 PM, Dennis Lee Bieber
 wrote:

> Ask yourself: Will my program still work if I remove all the assert
> statements. If the answer is "No", then you should not be using an assert.

You meant if the answer is "NO" then I should be using asset ?

> Can your "run()" raise an exception? Since you never show it to us we
> can't tell. And if it can, which ones? However, checking a return code is
> not an exceptional condition -- that's expected logic.
>

The run api is like a wrapper to sub-process module it does a Popen
run's the command and returns stdout ,err and ret. The only exception
it can raise is a timeout error.

>>try:
>>if not run_cmd_and_verify(cmd, timeout=3600):
>
> Since your version of rcav() always trapped exceptions internally, 
> this
> call will never raise an exception, so using a try: block is meaningless
>>return False
>
> And your conditional basically comes down to:
>
> if False:
> return False:
>
>
>>except:
>>   logging.error("Some meaningful message")
>>logging.info("Setup and Creation Done !!!")
>
> But you fall off and return Null on success...

Iam using the try expect block to loop over  the list do I have
alternatives  but would prefer the for loop because in the actual
program there are 100 of command and putting them in a list is quite
easy and running over with the same operation saves many lines of code
,  Cam I modify it something like a try except with pass in the except
? or any suggestions


for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
pass
logging.info("Setup and Creation Done !!!")

Regards,
Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: usage of try except for review.

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 4:34 AM, Ganesh Pal  wrote:
> On Mon, Feb 29, 2016 at 10:10 PM, Dennis Lee Bieber
>  wrote:
>
>> Ask yourself: Will my program still work if I remove all the assert
>> statements. If the answer is "No", then you should not be using an assert.
>
> You meant if the answer is "NO" then I should be using asset ?

No, Dennis was correct. You should assume that "assert" can
potentially be replaced with "pass" and your program will continue to
work.

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


Re: common mistakes in this simple program

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 10:26 AM, Ganesh Pal  wrote:
> On Mon, Feb 29, 2016 at 9:59 PM, Ian Kelly  wrote:
>> On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal  wrote:
>>> Iam on python 2.6
>
>>> 1. usage of try- expect
>>
>> try-except in every single function is a code smell. You should only
>> be using it where you're actually going to handle the exception. If
>> you catch an exception just to log it, you generally should also
>> reraise it so that something further up the call chain has the
>> opportunity to handle it.
>
> How do we reraise the exception in python ,  I have used raise not
> sure how to reraise the exception

raise with no arguments will reraise the exception currently being handled.

except Exception:
logging.error("something went wrong")
raise

>>> assert ret ==0,"ERROR (ret %d): " \
>>> " \nout: %s\nerr: %s\n" % (ret, out, err)
>>> except Exception as e:
>>> print("Failed to run %s got %s" % (cmd, e))
>>> return False
>>> return True
>>>
>>> def prep_host():
>>> """
>>> Prepare clustering
>>> """
>>> for cmd in ["ls -al",
>>> "touch /tmp/file1",
>>> "mkdir /tmp/dir1"]:
>>> try:
>>> if not run_cmd_and_verify(cmd, timeout=3600):
>>> return False
>>> except:
>>
>> What exceptions are you expecting this to catch? run_cmd_and_verify
>> already catches any expected exceptions that it raises.
>
> This is a wrapper for Popen it runs the command and returns stdout
> ,stderror and returncode .The only exception it can return is a time
> out exception

But that exception is already caught by the run_cmd_and_verify
function, so what exception are you expecting to be caught *here*?

> Here is the modified buggy code ,  Can I have Try and except with Pass
> , how do I modify the  try and expect in the pre-host ?

You should virtually never just pass in an exception handler. Either
handle the exception, or log it and reraise it. If you're going to do
neither of those things, then don't use a try-except at all.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Rustom Mody
On Monday, February 29, 2016 at 11:04:20 PM UTC+5:30, Ben Finney wrote:
> Rustom Mody writes:
> 
> > On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:
> > > Ian Kelly  writes:
> > > 
> > > > On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
> > > > > I found this to be a very sad story. Sure, he had some issues, but I
> > > > > don't think they needed to drug him, and take all that he had
> > > > > learned away from him and turn him back into what he was before.
> > > >
> > > > "All that he had learned" meaning his delusions and psychoses?
> > > 
> > > Indeed. If a revelation is unconnected to reality, it's misleading to
> > > say that one has "learned" it.
> >
> > And who is the last arbiter on that 'reality'?
> 
> A nice academic question. Not appropriate when we're discussing a real
> person's psychotic episodes. Neither you nor I are experts in whether an
> experience is psychosis, and the person already has an expert diagnosis.
> 
> So please don't de-rail into the weeds of second-guessing an expert in
> mental health. Unless you know the person's mental health better than
> their doctor (and you do not), don't second-guess the diagnosis they
> received.

No need to second guess

Article's last line:

Avoid falling in love with hyper-intelligent pan-dimensional beings.

IOW Larry makes an important point

The fact that he claims to be better now than in that period is more
significant than the medical diagnoses

It neglects the possibility that these are not the only two possibilities
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
> No, Dennis was correct. You should assume that "assert" can
> potentially be replaced with "pass" and your program will continue to
> work.

Thanks Chris for clarifying Dennis point of view  ,


>>try:
>>if not run_cmd_and_verify(cmd, timeout=3600):
>
> Since your version of rcav() always trapped exceptions internally, 
> this
> call will never raise an exception, so using a try: block is meaningless
>>return False
>
> And your conditional basically comes down to:
>
> if False:
> return False:


What would be the alternative for try expect  in the  FOR loop section
of the program ,  will this work fine i.e expect with pass , or any
better alternative for this ?

I have tried down the code to


#!/usr/bin/env python


"""
"""
import os
import shlex
import subprocess
import sys
import time
import logging
from utils import run

def run_cmd_and_verify(cmd, timeout=1000):

try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True

def run_test():
"""
Mount
"""
# For Loop section of the program
for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
 logging.error("mount Failed")
return False
except:
pass
logging.info("Setup and Creation Done !!!")

def main():
if not run_test():
sys.exit("Exiting Main")

if __name__ == '__main__':
main()


Regards,
Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
> I have tried down the code to

Read "I have tried down the code to "  as I have trimmed down the code  as below

Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Grant Edwards
On 2016-02-29, Chris Angelico  wrote:
> On Tue, Mar 1, 2016 at 2:43 AM, Grant Edwards  wrote:
>> On 2016-02-29, Chris Angelico  wrote:
>>
>>> Abjuring JS may be a virtue (or at least, making it a non-critical
>>> part of your web site),
>>
>> Except the marketing people who decide on the requirements will never,
>> ever settle for what you can do with plain HTML/CSS.
>>
>> In my experience, HTML/CSS makes a pretty awful GUI for a non-trivial
>> application.  With some Javascript and sweat, you can almost make it
>> to mediocre.
>
> That's why I said "may be". A pure CGI web site is pretty annoying
> unless it's really brilliantly done. However, I prefer to see JS
> restricted to actual interaction, instead of making it critical to the
> basic layout.

Agreed. That's an excellent rule to follow.  The introduction of the
"flex" display type in CSS has (for me) completely eliminated the need
for JS to concern itself with display and layout (other than the basic
hide/show enable/disable of optional elements as part of an
application's interaction logic).

I don't know why it took so long for CSS to grok the basic idea that
you almost always want to specify that some blocks should
expand/contract to fill available space and some should remain at
their "natural" size.  GUI toolkits and markup languages like LaTeX
seem to have understood that this was a very basic need for many
decades, but there was never a clean, reliable way to do it CSS until
recently.

> A lot of web sites these days load nothing but a script
> that goes and loads everything else, while you gaze at a splash
> screen. IMO that's unideal.

:)

"Unideal" is too kind -- I would described it as something more like
"the evil spawn of brain-dead incompetents".  I often wonder what
sequence of decisions/accidents get people to "solutions" like that.

> However, even that is probably a losing battle. :(

At least the era of using giant tables full of fragements of a single
large gif image to do page-layout seems to have died a long-overdue
death...

-- 
Grant Edwards   grant.b.edwardsYow! does your DRESSING
  at   ROOM have enough ASPARAGUS?
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Ganesh Pal
>> How do we reraise the exception in python ,  I have used raise not
>> sure how to reraise the exception
>
> raise with no arguments will reraise the exception currently being handled.
>
> except Exception:
> logging.error("something went wrong")
> raise

Thanks Ian for taking time and looking into the code ,  o k raise
keyword for raising exception is fine .

 assert ret ==0,"ERROR (ret %d): " \
 " \nout: %s\nerr: %s\n" % (ret, out, err)
 except Exception as e:
 print("Failed to run %s got %s" % (cmd, e))
 return False
 return True

 def prep_host():
 """
 Prepare clustering
 """
 for cmd in ["ls -al",
 "touch /tmp/file1",
 "mkdir /tmp/dir1"]:
 try:
 if not run_cmd_and_verify(cmd, timeout=3600):
 return False
 except:
>>>
>>> What exceptions are you expecting this to catch? run_cmd_and_verify
>>> already catches any expected exceptions that it raises.

In my case the exception is nothing but the error  example if  we plan
to run the command  say  #ifconfig -a and the command fails because of
a type ( say u ran #igconfig -a).

we will the output as

# Failed to run igconfig -a got Error (ret=127)
out :
error: command not found: igconfig

So the execption is the error i.e Error (ret=127) out : error: command
not found: igconfig,  Iam fine with this behaviour.


>
> But that exception is already caught by the run_cmd_and_verify
> function, so what exception are you expecting to be caught *here*?

I wanted to run the command in a loop  and have a fxn for the pattern
that repeats in this case the function is run_cmd_and_verify  , the
only known way to me was using try with expect

I thought I will use try and have pass in except which  you don't recommend

   for cmd in ["ls -al",
 "touch /tmp/file1",
"mkdir /tmp/dir1"]:
  try:
   if not run_cmd_and_verify(cmd, timeout=3600):
print "running command failed "
   return False
except:
pass

> You should virtually never just pass in an exception handler. Either
> handle the exception, or log it and reraise it. If you're going to do
> neither of those things, then don't use a try-except at all.

What alternative do I have other than try-expect ? can try - else be
used  for my case?

Regards,
GPal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sending an email with a binary attachment

2016-02-29 Thread Grant Edwards
On 2016-02-29, Peter Pearson  wrote:
> On Mon, 29 Feb 2016 02:10:00 -0600, Anthony Papillion wrote:
>
>> For some reason though, sending mail is failing every time. I've made
>> sure that the password is correct (which seems to be the most usual
>> error).
>>
>> Still, I just can't get it to work. Can someone take a look at this
>> code and give me some advice?
>
> What exactly do you mean by "failing"?  If there's an error message,
> show it.  If an exception is being generated, at least print some
> information about the exception.

If you aren't getting any messages, then tell the smtp object you want some:

>From TFM (https://docs.python.org/3/library/smtplib.html#smtp-objects):

  An SMTP instance has the following methods:

   SMTP.set_debuglevel(level)

  Set the debug output level. A value of 1 or True for level
  results in debug messages for connection and for all messages
  sent to and received from the server. A value of 2 for level
  results in these messages being timestamped.

If all else fails, fire up wireshark and watch the conversation
between the SMTP object and the server.

-- 
Grant Edwards   grant.b.edwardsYow! Can you MAIL a BEAN
  at   CAKE?
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 5:17 AM, Grant Edwards  wrote:
>> A lot of web sites these days load nothing but a script
>> that goes and loads everything else, while you gaze at a splash
>> screen. IMO that's unideal.
>
> :)
>
> "Unideal" is too kind -- I would described it as something more like
> "the evil spawn of brain-dead incompetents".  I often wonder what
> sequence of decisions/accidents get people to "solutions" like that.

I do understand where the thinking comes from, though.

1) Pages should be more responsive than the 1990s-style CGI model,
where every action is a link or button click that completely replaces
the current page.
2) Many actions therefore must be implemented using JavaScript, an
AJAX call (if necessary), and DOM manipulation to change just the
parts of the page that need to be changed.
3) This means that the entire content of the page must be under JS
control, and the entire "user-accessible" part of the back end should
be returning JSON, since that's what #2 requires.
4) If everything has to be under JS control, why not just send out a
stub to start with, and begin everything with an AJAX call? That way,
we don't need to maintain two of everything!

The logic is reasonable. Deduplication is valuable. But the result is
a web site that has a stubby splash screen until the back end
responds, and that's why I call it merely "unideal" rather than "evil
spawn &c".

>> However, even that is probably a losing battle. :(
>
> At least the era of using giant tables full of fragements of a single
> large gif image to do page-layout seems to have died a long-overdue
> death...

Oh yes, I do not miss those days! And it was compounded by browsers
that, when they started receiving a  tag, drew nothing
whatsoever until they received the  and could lay the whole
thing out. Add to that slow internet connections, so it would likely
be some seconds or even a minute or more before the  arrives,
and you have a perfect recipe for frustration.

But no web site these days would ever make you wait for its contents.
'Course not.

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


Re: common mistakes in this simple program

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 5:21 AM, Ganesh Pal  wrote:
>
> In my case the exception is nothing but the error  example if  we plan
> to run the command  say  #ifconfig -a and the command fails because of
> a type ( say u ran #igconfig -a).
>
> we will the output as
>
> # Failed to run igconfig -a got Error (ret=127)
> out :
> error: command not found: igconfig
>
> So the execption is the error i.e Error (ret=127) out : error: command
> not found: igconfig,  Iam fine with this behaviour.
>

You're falling into the trap of assuming that the only exception you
can ever get is the one that you're planning for, and then handling
ALL exceptions as though they were that one. Instead catch ONLY the
exception that you're expecting to see, and ignore everything else. Do
not use a bare "except:" clause, nor even "except Exception:", for
this. You will appreciate it later on.

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


Re: common mistakes in this simple program

2016-02-29 Thread sohcahtoa82
On Monday, February 29, 2016 at 10:21:57 AM UTC-8, Ganesh Pal wrote:
> >> How do we reraise the exception in python ,  I have used raise not
> >> sure how to reraise the exception
> >
> > raise with no arguments will reraise the exception currently being handled.
> >
> > except Exception:
> > logging.error("something went wrong")
> > raise
> 
> Thanks Ian for taking time and looking into the code ,  o k raise
> keyword for raising exception is fine .
> 
>  assert ret ==0,"ERROR (ret %d): " \
>  " \nout: %s\nerr: %s\n" % (ret, out, err)
>  except Exception as e:
>  print("Failed to run %s got %s" % (cmd, e))
>  return False
>  return True
> 
>  def prep_host():
>  """
>  Prepare clustering
>  """
>  for cmd in ["ls -al",
>  "touch /tmp/file1",
>  "mkdir /tmp/dir1"]:
>  try:
>  if not run_cmd_and_verify(cmd, timeout=3600):
>  return False
>  except:
> >>>
> >>> What exceptions are you expecting this to catch? run_cmd_and_verify
> >>> already catches any expected exceptions that it raises.
> 
> In my case the exception is nothing but the error  example if  we plan
> to run the command  say  #ifconfig -a and the command fails because of
> a type ( say u ran #igconfig -a).
> 
> we will the output as
> 
> # Failed to run igconfig -a got Error (ret=127)
> out :
> error: command not found: igconfig
> 
> So the execption is the error i.e Error (ret=127) out : error: command
> not found: igconfig,  Iam fine with this behaviour.
> 
> 
> >
> > But that exception is already caught by the run_cmd_and_verify
> > function, so what exception are you expecting to be caught *here*?
> 
> I wanted to run the command in a loop  and have a fxn for the pattern
> that repeats in this case the function is run_cmd_and_verify  , the
> only known way to me was using try with expect
> 
> I thought I will use try and have pass in except which  you don't recommend
> 
>for cmd in ["ls -al",
>  "touch /tmp/file1",
> "mkdir /tmp/dir1"]:
>   try:
>if not run_cmd_and_verify(cmd, timeout=3600):
> print "running command failed "
>return False
> except:
> pass
> 
> > You should virtually never just pass in an exception handler. Either
> > handle the exception, or log it and reraise it. If you're going to do
> > neither of those things, then don't use a try-except at all.
> 
> What alternative do I have other than try-expect ? can try - else be
> used  for my case?
> 
> Regards,
> GPal

Every time you say "try-expect", my head wants to explode.

It is called a "try-except" block, because you're using the key words "try" and 
"except" when you make one.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Ganesh Pal
On Mar 1, 2016 12:06 AM, "Chris Angelico"  wrote
>
> You're falling into the trap of assuming that the only exception you
> can ever get is the one that you're planning for, and then handling.

Ok sure !

> ALL exceptions as though they were that one. Instead catch ONLY the
> exception that you're expecting to see, and ignore everything else. Do
> not use a bare "except:" clause, nor even "except Exception:", for
> this. You will appreciate it later on.

What option do I have now in  so ensure that I loop over the For loop. Try
except is ruled out ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Loop awareness

2016-02-29 Thread jonas . thornvall
This program creates a uniform linktree of x nodes, and it knows when it get 
stuck in a loop generating random values.

Because the networks random generated, only a subset of the permutations will 
generate a uniform network most get stuck in loops generating random values. 
But the program keep track the exhausted links and knows when no uniform 
network possible.

Is this related to the halting problem?

http://jt.node365.se/mydebug1.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 2:49 PM, Ganesh Pal  wrote:

> On Mar 1, 2016 12:06 AM, "Chris Angelico"  wrote
> >
> > You're falling into the trap of assuming that the only exception you
> > can ever get is the one that you're planning for, and then handling.
>
> Ok sure !
>
> > ALL exceptions as though they were that one. Instead catch ONLY the
> > exception that you're expecting to see, and ignore everything else. Do
> > not use a bare "except:" clause, nor even "except Exception:", for
> > this. You will appreciate it later on.
>
> What option do I have now in  so ensure that I loop over the For loop. Try
> except is ruled out ?
>

Its not ruled out.  It is pointless.  Look at the documents.  Here is a
start: https://wiki.python.org/moin/HandlingExceptions

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



-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Marko Rauhamaa
[email protected]:

> Every time you say "try-expect", my head wants to explode.
>
> It is called a "try-except" block, because you're using the key words
> "try" and "except" when you make one.

Ah, I remember a Python-based test system idea where the "except"
keyword meant "expect":

try: event()
except user.CloseRequest():
...
except user.SendRequest():
...
except peer.DataIndication():
...
except Timeout():
...

etc.

In the end, though, we came up with something better.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Loop awareness

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 1:07 PM,   wrote:
> This program creates a uniform linktree of x nodes, and it knows when it get 
> stuck in a loop generating random values.
>
> Because the networks random generated, only a subset of the permutations will 
> generate a uniform network most get stuck in loops generating random values. 
> But the program keep track the exhausted links and knows when no uniform 
> network possible.
>
> Is this related to the halting problem?
>
> http://jt.node365.se/mydebug1.html

No, the halting problem is that you can't algorithmically determine
whether an *arbitrary* program given *arbitrary* input will ever halt.
When you narrow down the scope of the problem considerably, as you've
done here, then it's no longer necessarily undecidable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Martin A. Brown

Greetings Ganesh,

>> You're falling into the trap of assuming that the only exception you
>> can ever get is the one that you're planning for, and then handling.
>
>Ok sure !

This point is very important, so I'll reiterate it.  I hope the poor 
horse lives.

>> ALL exceptions as though they were that one. Instead catch ONLY the
>> exception that you're expecting to see, and ignore everything else. Do
>> not use a bare "except:" clause, nor even "except Exception:", for
>> this. You will appreciate it later on.
>
>What option do I have now in so ensure that I loop over the For 
>loop. 

>Try except is ruled out ?

No, no not at all!

  #1:  Yes, you (probably) should be using the try-except construct.
  #2:  No, you should not (ever) use a bare try-except construct.

Please read below.  I will take a stab at explaining the gaps of 
understanding you seem to have (others have tried already, but I'll 
try, as well).

I am going to give you four different functions which demonstrate 
how to use exceptions.  You may find it instructive to paste these 
functions into an interactive Python shell and try them out, as 
well.

I will explain a few different cases, which I will show below, but I 
think you'll need to figure out how to apply this to your situation.


Step 1: catch a specific Exception
--

  def catchValueError(val, default=0):
  '''somebody passed in a non-convertible type, return a default'''
  try:
  return int(val)
  except ValueError:
  return default

Now, let's try passing a few values into that function:

  >>> catchValueError(0)
  0
  >>> catchValueError('-3')
  -3
  >>> catchValueError('Catullus')
  0

The last example above is the most interesting.  We fed a string to 
the builtin function int() and it raised a ValueError.  Our little 
try-except block, however, caught the ValueError and performed our 
desired action (in this case, returning a default value).


Step 2: catch a specific Exception
--

But, what about this:

  >>> catchValueError(dict())
  Traceback (most recent call last):
File "", line 1, in 
File "", line 4, in catchValueError
  TypeError: int() argument must be a string or a number, not 'dict'

Now, you can see that there's a different problem.  The exception is 
different if we feed different data to the function.  So, let's try 
again, but maybe we catch the TypeError instead.

  def catchTypeError(val, default=0):
'''somebody passed in a non-convertible type, return a default'''
try:
return int(val)
except TypeError:
return default

This seems to work--but, now, if we try our other values (which 
worked before), they don't work now:

  >>> catchTypeError(dict())
  0
  >>> catchTypeError(0)
  0
  >>> catchTypeError('-3')
  -3
  >>> catchTypeError('Catullus')
  Traceback (most recent call last):
File "", line 1, in 
File "", line 4, in catchTypeError
  ValueError: invalid literal for int() with base 10: 'Catullus'


Step 3: catch several different classes of Exception


You can a single try-except block to catch multiple classes of 
specific Exception (and then perform exception handling).

  def catchTVError(val, default=0):
'''somebody passed in a non-convertible type, return a default'''
try:
return int(val)
except (ValueError, TypeError):
return default

In this little toy demonstration, you can see that this is probably 
the desired functionality.

  >>> catchTVError(dict())
  0
  >>> catchTVError(0)
  0
  >>> catchTVError(-3)
  -3
  >>> catchTVError('Catullus')
  0


Step 4: catch many different classes of Exception
-

Now, suppose you want to deal with each possible exception in a different
manneryou can have different exception-handling behaviour for each class of
exception.

  def altCatchTVError(val, default=42):
  '''somebody passed in a non-convertible type, return a default'''
  try:
  return int(val)
  except ValueError:
  return abs(default)
  except TypeError:
  return 0 - abs(default)

As you can see, this offers a good deal more flexibility for handling specific
exceptions that you might encounter.

  >>> altCatchTVError(0)
  0
  >>> altCatchTVError(22)
  22
  >>> altCatchTVError('17')
  17
  >>> altCatchTVError('-3')
  -3
  >>> altCatchTVError('str')
  42
  >>> altCatchTVError(dict())
  -42


Interlude and recommendation


As you can see, there are many possible Exceptions that can be raised when you
are calling a simple builtin function, int().

Consider now what may happen when you call out to a different program; you
indicated that your run() function calls out to subprocess.Popen().  There are
many more possible errors that can occur, just a few that can come to my mind:

  * locating the program on disk
  * setting u

Re: Loop awareness

2016-02-29 Thread jonas . thornvall
Den måndag 29 februari 2016 kl. 21:32:51 UTC+1 skrev Ian:
> On Mon, Feb 29, 2016 at 1:07 PM,   wrote:
> > This program creates a uniform linktree of x nodes, and it knows when it 
> > get stuck in a loop generating random values.
> >
> > Because the networks random generated, only a subset of the permutations 
> > will generate a uniform network most get stuck in loops generating random 
> > values. But the program keep track the exhausted links and knows when no 
> > uniform network possible.
> >
> > Is this related to the halting problem?
> >
> > http://jt.node365.se/mydebug1.html
> 
> No, the halting problem is that you can't algorithmically determine
> whether an *arbitrary* program given *arbitrary* input will ever halt.
> When you narrow down the scope of the problem considerably, as you've
> done here, then it's no longer necessarily undecidable.

Here i told it to only report the unfiorm subset of working networks.



http://jt.node365.se/mydebug2.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Request More Help With XBM Image

2016-02-29 Thread Wildman via Python-list
I want to take an image file, convert it to XBM format and
display it.  Thanks to Mr. Otten I can open and display the
XBM image without any problems.  The script first calls an
external program for the image conversion then I can open
and display it.  Of course, I am left with the XBM file that
needs to be deleted.  It seemed to me to be a better approach
to use stdout and pipe thereby eliminating the XBM file
altogether.  Here is code I have so far but I'm not sure
what to do next...

convert = "convert " + fileName + " -resize 48x48! -threshold 55% xbm:-"
p = subprocess.Popen([convert], stdout=subprocess.PIPE, shell=True)
xbmFile, err = p.communicate()

The variable fileName contains the image file path and name.
The variable convert contains the complete command.  The last
argument in the command tells the convert utility to covert
to an XBM and to direct the output to stdout.  After the above
code runs xbmFile contains the actual image, which is plain
text.  (X BitMap (XBM) is a plain text binary image format.)

My question is how do I take the xbmFile variable and convert
it to an image object that can be displayed?  The technique
for displaying an image from a file does not work or at least
I have not been able to get it to work.

-- 
 GNU/Linux user #557453
"Be at war with your vices, at peace with your neighbors,
and let every new year find you a better man."
  -Benjamin Franklin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Larry Martell
On Mon, Feb 29, 2016 at 11:47 AM, Ian Kelly  wrote:
> On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  
> wrote:
>> On Sat, Feb 27, 2016 at 4:37 AM, Steven D'Aprano  wrote:
>>> The author of Requests, Kenneth Reitz, discusses his recent recovery from a
>>> MentalHealthError exception.
>>>
>>> http://www.kennethreitz.org/essays/mentalhealtherror-an-exception-occurred
>>>
>>> Although the connection to Python is only quite slim, I found it fascinating
>>> to read.
>>
>> I found this to be a very sad story. Sure, he had some issues, but I
>> don't think they needed to drug him, and take all that he had learned
>> away from him and turn him back into what he was before.
>
> "All that he had learned" meaning his delusions and psychoses?

How do you know they were delusions? I think his only problem was not
sleeping, which can kill you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Larry Martell
On Mon, Feb 29, 2016 at 11:56 AM, Ben Finney  wrote:
> Ian Kelly  writes:
>
>> On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  
>> wrote:
>> > I found this to be a very sad story. Sure, he had some issues, but I
>> > don't think they needed to drug him, and take all that he had
>> > learned away from him and turn him back into what he was before.
>>
>> "All that he had learned" meaning his delusions and psychoses?
>
> Indeed. If a revelation is unconnected to reality, it's misleading to
> say that one has “learned” it.

But what is reality?

> Also, I don't see how anyone “took away” those experiences. He wrote an
> article describing them and clearly still retains those experiences as
> memories to recall as he wishes.

They made him believe they were not true.

> When someone describes the ill effects their mental illness produced,

I don't consider him to have been mentally ill.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Larry Martell
On Mon, Feb 29, 2016 at 12:33 PM, Ben Finney  wrote:
> Rustom Mody  writes:
>
>> On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:
>> > Ian Kelly  writes:
>> >
>> > > On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
>> > > > I found this to be a very sad story. Sure, he had some issues, but I
>> > > > don't think they needed to drug him, and take all that he had
>> > > > learned away from him and turn him back into what he was before.
>> > >
>> > > "All that he had learned" meaning his delusions and psychoses?
>> >
>> > Indeed. If a revelation is unconnected to reality, it's misleading to
>> > say that one has "learned" it.
>>
>> And who is the last arbiter on that 'reality'?
>
> A nice academic question. Not appropriate when we're discussing a real
> person's psychotic episodes. Neither you nor I are experts in whether an
> experience is psychosis, and the person already has an expert diagnosis.
>
> So please don't de-rail into the weeds of second-guessing an expert in
> mental health. Unless you know the person's mental health better than
> their doctor (and you do not), don't second-guess the diagnosis they
> received.

I think for the most part, the mental health industry is most
interested in pushing drugs and forcing people into some status quo.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Cameron Simpson

On 29Feb2016 10:45, Ian Kelly  wrote:

On Mon, Feb 29, 2016 at 10:26 AM, Ganesh Pal  wrote:

On Mon, Feb 29, 2016 at 9:59 PM, Ian Kelly  wrote:

On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal  wrote:

1. usage of try- expect


try-except in every single function is a code smell. You should only
be using it where you're actually going to handle the exception. If
you catch an exception just to log it, you generally should also
reraise it so that something further up the call chain has the
opportunity to handle it.


How do we reraise the exception in python ,  I have used raise not
sure how to reraise the exception


raise with no arguments will reraise the exception currently being handled.

except Exception:
   logging.error("something went wrong")
   raise


Another remark here: if you're going to log, log the exception as well:

logging.error("something went wrong: %s", e)

Ian's example code is nice and simple to illustrate "log and then reraise" but 
few things are as annoying as log files reciting "something went wrong" or the 
equivalent without any accompanying context information.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Rob Gaddi
Cameron Simpson wrote:

> On 29Feb2016 10:45, Ian Kelly  wrote:
>>On Mon, Feb 29, 2016 at 10:26 AM, Ganesh Pal  wrote:
>>> On Mon, Feb 29, 2016 at 9:59 PM, Ian Kelly  wrote:
 On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal  wrote:
> 1. usage of try- expect

 try-except in every single function is a code smell. You should only
 be using it where you're actually going to handle the exception. If
 you catch an exception just to log it, you generally should also
 reraise it so that something further up the call chain has the
 opportunity to handle it.
>>>
>>> How do we reraise the exception in python ,  I have used raise not
>>> sure how to reraise the exception
>>
>>raise with no arguments will reraise the exception currently being handled.
>>
>>except Exception:
>>logging.error("something went wrong")
>>raise
>
> Another remark here: if you're going to log, log the exception as well:
>
>  logging.error("something went wrong: %s", e)
>
> Ian's example code is nice and simple to illustrate "log and then reraise" 
> but 
> few things are as annoying as log files reciting "something went wrong" or 
> the 
> equivalent without any accompanying context information.
>
> Cheers,
> Cameron Simpson 

Or, for that matter:

  logging.exception('something went wrong')

Which gives you the whole traceback as well and doesn't require you to
explictly grab the exception.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Mark Lawrence

On 29/02/2016 22:40, Larry Martell wrote:

On Mon, Feb 29, 2016 at 12:33 PM, Ben Finney  wrote:

Rustom Mody  writes:


On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:

Ian Kelly  writes:


On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:

I found this to be a very sad story. Sure, he had some issues, but I
don't think they needed to drug him, and take all that he had
learned away from him and turn him back into what he was before.


"All that he had learned" meaning his delusions and psychoses?


Indeed. If a revelation is unconnected to reality, it's misleading to
say that one has "learned" it.


And who is the last arbiter on that 'reality'?


A nice academic question. Not appropriate when we're discussing a real
person's psychotic episodes. Neither you nor I are experts in whether an
experience is psychosis, and the person already has an expert diagnosis.

So please don't de-rail into the weeds of second-guessing an expert in
mental health. Unless you know the person's mental health better than
their doctor (and you do not), don't second-guess the diagnosis they
received.


I think for the most part, the mental health industry is most
interested in pushing drugs and forcing people into some status quo.



I am disgusted by your comments.  I'll keep my original reply in reserve.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Joel Goldstick
On Mon, Feb 29, 2016 at 6:29 PM, Mark Lawrence 
wrote:

> On 29/02/2016 22:40, Larry Martell wrote:
>
>> On Mon, Feb 29, 2016 at 12:33 PM, Ben Finney 
>> wrote:
>>
>>> Rustom Mody  writes:
>>>
>>> On Monday, February 29, 2016 at 10:26:32 PM UTC+5:30, Ben Finney wrote:

> Ian Kelly  writes:
>
> On Mon, Feb 29, 2016 at 9:21 AM, Larry Martell  wrote:
>>
>>> I found this to be a very sad story. Sure, he had some issues, but I
>>> don't think they needed to drug him, and take all that he had
>>> learned away from him and turn him back into what he was before.
>>>
>>
>> "All that he had learned" meaning his delusions and psychoses?
>>
>
> Indeed. If a revelation is unconnected to reality, it's misleading to
> say that one has "learned" it.
>

 And who is the last arbiter on that 'reality'?

>>>
>>> A nice academic question. Not appropriate when we're discussing a real
>>> person's psychotic episodes. Neither you nor I are experts in whether an
>>> experience is psychosis, and the person already has an expert diagnosis.
>>>
>>> So please don't de-rail into the weeds of second-guessing an expert in
>>> mental health. Unless you know the person's mental health better than
>>> their doctor (and you do not), don't second-guess the diagnosis they
>>> received.
>>>
>>
>> I think for the most part, the mental health industry is most
>> interested in pushing drugs and forcing people into some status quo.
>>
>>
> I am disgusted by your comments.  I'll keep my original reply in reserve.
>
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

I really like requests.  I recommend it whenever people have trouble with
urllib.  As to Kenneth's personal struggle, good for him.  An interesting
and honest appraisal of his personal stuff.  Viva la internet

-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: common mistakes in this simple program

2016-02-29 Thread Ian Kelly
On Mon, Feb 29, 2016 at 4:14 PM, Cameron Simpson  wrote:
> Another remark here: if you're going to log, log the exception as well:
>
> logging.error("something went wrong: %s", e)
>
> Ian's example code is nice and simple to illustrate "log and then reraise"
> but few things are as annoying as log files reciting "something went wrong"
> or the equivalent without any accompanying context information.

The proper way to pass in the exception is as a keyword argument:

logging.error("something went wrong", exc_info=e)

But I actually meant to use logging.exception, which handles this automatically.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Paul Rubin
Ben Finney  writes:
>> "All that he had learned" meaning his delusions and psychoses?
> Indeed. If a revelation is unconnected to reality, it's misleading to
> say that one has “learned” it
> When someone describes the ill effects their mental illness produced, I
> find it rather condescending for an observer to express regret that
> the person no longer experiences those ill effects.

The story reminded me of "A Beautiful Mind" by Sylvia Nasar, about
mathematician John Nash who suffered from mental illness in the
1970s-80's(?) but later recovered and won the Nobel Prize in economics.
The book is excellent and I recommend it if you find that sort of thing
interesting.  They made a movie from it that was popular but I gather
was Hollywood-fluffified as one could expect (I haven't seen it).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Ethan Furman

On 02/29/2016 04:35 PM, Paul Rubin wrote:


The story reminded me of "A Beautiful Mind" by Sylvia Nasar, about
mathematician John Nash who suffered from mental illness in the
1970s-80's(?) but later recovered and won the Nobel Prize in economics.
The book is excellent and I recommend it if you find that sort of thing
interesting.  They made a movie from it that was popular but I gather
was Hollywood-fluffified as one could expect (I haven't seen it).


I'm sure it was fluffified, but it is a good movie.

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Paramiko Help. Execute command to Interactive Shell which is opened by SSHClient()

2016-02-29 Thread reachparagm
Sagar,

Have you worked on RobotFramework-sshlibrary. It seem to have very simple 
interface for both command processing/execution as well as interactive session 
to grep responses and decide the flow.

Let me know if you face any issues. Can help you solve.

-paragm

On Thursday, August 8, 2013 at 12:20:25 AM UTC-7, sagar varule wrote:
> Hi All,
> 
> Im using Paramiko for my SSH automation. Im using method that is shown in 
> demo_simple.py example which comes with Paramiko. Below is code from 
> demo_simple.py.
> 
> As you can make out, below code opens SSH connection and opens Interactie 
> Shell, and then wait for the command from user.
> I want to submit the command to this Interactive Shell using code.
> 
> try:
> client = paramiko.SSHClient()
> client.load_system_host_keys()
> client.set_missing_host_key_policy(paramiko.WarningPolicy())
> print '*** Connecting...'
> client.connect(hostname, port, username, password)
> chan = client.invoke_shell()
> print repr(client.get_transport())
> print '*** Here we go!'
> print
> interactive.interactive_shell(chan)
> chan.close()
> client.close()
> 
> Well Another approach I tried is instead of opening interactive_shell, 
> directly issue command using;
> 
>  stdin, stdout, stderr = client.exec_command(bv_cmd)
> for line in stderr.readlines():
> print line
> for line in stdout.readlines():
> print line
> But problem here is client.exec_command(bv_cmd) waits for command to execute 
> completely and then it returns to stdout,stderr. And I want to see the ouput 
> from the command during its execution. Because my command takes long time for 
> execution.
> 
> Big Picture in My Mind: Big Picture I that want to achieve is, Opening 
> different SSH connection to different host, and it will issue commands to all 
> host, wait for execution. All execution should happen parallel.(just wanted 
> to share my thought, and wanted to hear opinions from you all. Is this 
> possible??). I am not big programmer, just 2 years experience with asp.net C# 
> 2.0 so i would appreciate if discussion happens in simple english.

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


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Terry Reedy

On 2/29/2016 3:20 AM, Chris Angelico wrote:


Incidentally, HTML+CSS is another excellent example of code being used
to create a visual effect. While there *are* WYSIWYG HTML editors, I'm
not familiar with any WYISWYG HTML+CSS editors, and I much more often
see a fast-turnaround code editing system such as codepen.io - you
change the HTML in one box, or the CSS in another, and the result down
below changes in real-time.


Does it change with each key stroke (if the keystroke leaves the text in 
a coherent, non-error state) or only on some special input?



It wouldn't be too hard to create
something like this for a GUI, and it'd remove some of that feeling of
non-interactivity while still retaining all the benefits of code above
drag-and-drop.


Keystroke auto-updates hardly make sense.  On-demand updates for tkinter 
are already possible.  By default, tk root windows, Python interpreter, 
Idle Shell, and IDLE Editors windows appear in the upper left of a 
screen.  Move either the tk or the python window(s) to the right.



1. REPL (python or IDLE): Possible updates are signaled by \n.  Tkinter 
visibly responds, when appropriate, on a statement by statement basis.


>>> import tkinter as tk
>>> root = tk.Tk()  # root window appears
>>> b = tk.Button(root)  # text='', bg='white' are defaults
>>> b.grid()  # button appears in root window
>>> b['text'] = 'Hello World!'  # text appears in button
>>> b['bg'] = 'red'  # background color changes

(Non-default options can also be set when a widget is created.)
One can even, I just discovered, setup timer events interactively.

>>> root.after(500, lambda: b.config(bg='blue', text='done'))
# after 1/2 second (500 milliseconds), bg and text change

The disadvantage of this method is that the REPL record must be saved 
and processed to reuse it.



2. Editor (IDLE): Run with F5 to see the result of any changes.  The 
root window appears in a fraction of a second and population by widgets 
hardly takes much longer.  I think that this is close enough to 
interactive for most purposes.



3. Editor + REPL (IDLE): Since F5 simulates running the file with 
'python -i', this is automatic if the file in the editor does not run 
'root.mainloop()'.  If it does, the following in the file will allow one 
to end the blocking mainloop() call without also calling root.destroy 
and destroying the gui.


tk.Button(root, text='quit mainloop', command=root.quit).grid()


4. Integrated Editor and Display: your idea.  I think "It wouldn't be 
too hard" is wildly over-optimistic, as I will now explain>


The turtle demo (python -m turtledemo) has read-only text on the left, a 
turtle screen on the right, and a 'Start' button.  The text is read-only 
to avoid overwriting the supplied demo files.  People who want to edit 
them are supposed to copy and paste into an editor, such as IDLE's.)


The demo files must be and are (after failures) written in a special 
style to run properly within the demo framework, ... and to not disturb 
the buildbots when imported as part of test/test_all.  Top level code 
should only have definitions, including a 'def main' entry point, 
non-gui statements, and a '__main__'-guarded conditional statement for 
initiating gui actions.  They must also not bypass the turtle wrapping 
of tkinter to make direct tkinter calls that would disable the demo 
runner itself.  So even if turtledemo were turned into turtle-designer, 
by replacing the text pane with an editor, it could not be used for all 
legal turtle programs.


A GUI designer would replace the turtle screen also, with a gui frame. 
The special style would be something like the following template.


import tkinter as tk  # or "from tkinter import x, y, z, ..."
# define classes and functions

def main(parent):
# call classes, passing parent
# set up timers with parent.after
# anything else requiring that root exist

if __name__ == '__main__':
root = tk.Tk()
main(root)
root.mainloop()

The important point is that it must be possible to import the script 
without it creating a new root window or creating events. The app would 
run the user code with


user_gui = importlib.import_module(file_path)
user_gui.main(gui_frame)

Importing the code after saving, rather than using exec on the editor 
contents, isolates it somewhat from the app, but not enough.  Passing 
app's gui_frame into main and making that the parent of everything in 
the user gui ties the user gui into the app.  However, it also allows 
the app to inadvertently affect the app.  Non-interference between IDLE 
and user code, especially tkinter code, was the reason that IDLE was 
re-written, around a decade ago, to run user code in a separate process.


Another issue is handling user code errors.  Syntax errors can be marked 
in the editor, but tracebacks need a separate pane.  And it is also 
useful to be able to interact with the gui without altering the code in 
the editor.


Summary: if one starts with the idea of an inte

Re: [Off-topic] Requests author discusses MentalHealthError exception

2016-02-29 Thread Mario R. Osorio
On Saturday, February 27, 2016 at 4:39:12 AM UTC-5, Steven D'Aprano wrote:
> The author of Requests, Kenneth Reitz, discusses his recent recovery from a
> MentalHealthError exception.
> 
> http://www.kennethreitz.org/essays/mentalhealtherror-an-exception-occurred
> 
> Although the connection to Python is only quite slim, I found it fascinating
> to read.
> 
> 
> 
> -- 
> Steven


Live and let live, but DO learn from other's experiences in the mean time 
otherwise, your life has been wasted.

If you are one of those "hyper-intelligent pan-dimensional beings", good for 
you! but I think he made it very clear that is NOT what he should have been 
into.

Larry, you seem to know nothing about the mental health system(s) and might 
actually be in desperate need for help.

I myself have been helped A LOT with the right combination of psychologists, 
psychiatric doctors and medication.

You just have to be careful when selecting those professionals.

Larry ... just get a life ... for yourself.

(OH, and avoid new age and the such!!)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 1:33 PM, Terry Reedy  wrote:
> On 2/29/2016 3:20 AM, Chris Angelico wrote:
>
>> Incidentally, HTML+CSS is another excellent example of code being used
>> to create a visual effect. While there *are* WYSIWYG HTML editors, I'm
>> not familiar with any WYISWYG HTML+CSS editors, and I much more often
>> see a fast-turnaround code editing system such as codepen.io - you
>> change the HTML in one box, or the CSS in another, and the result down
>> below changes in real-time.
>
>
> Does it change with each key stroke (if the keystroke leaves the text in a
> coherent, non-error state) or only on some special input?

In the case of codepen, it's not quite either; when you finish typing
and leave it for half a second, it updates. Not quite instant, but
automiatic.

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


Condition fullfilled to early but only "sometimes"

2016-02-29 Thread jonas . thornvall
I've been looking at the code for two days so i am a bit crosseyed.
If anyone could help me set the condition so the loop catch the last 
pair/pairs, it is kind of weird that it succeed sometimes and break to early 
and report fail others.

I would be very greatful if anyone can see why it break to early and return 
fail. Although it is clearly a succes looking at the last remaining pair none 
connected pair.It should report fail for the network permutations that stall 
due to link exhausting, but not stall creating last pair.

It just a minor bug due to some condition that i just not get.
Have a go 5 munutes maybe someone catch the faulthy condition.

http://jt.node365.se/mydebug1.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Correct IDLE usage (was Reason for not allowing import twice but allowing reload())

2016-02-29 Thread Terry Reedy

On 2/29/2016 7:42 AM, Rustom Mody wrote:


Is import needed at all when trying out in Idle?

...

So it does appear that
1. import not necessary with(in) idle
2. However import and f5 (ie is run as main) are different

May some idle experts elaborate on this? Whats the idle idiom of import-ing?


Rustom, since I know that you are not a rank beginner, I have trouble 
understanding what you are asking.  F5 when editing foo.py is equivalent 
to running "python -i foo.py" on a command line while 'in' the directory 
containing foo.py.  In both cases, foo.py is run as a main module, with 
__name__ == '__main__'.  The difference is that F5 runs foo.py under 
IDLE supervision, with results going into and interactive inputs coming 
from IDLE shell instead of the console interpreter.


Imports are used in a module to access objects within the imported module.

--
Terry Jan Reedy


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


Re: Reason for not allowing import twice but allowing reload()

2016-02-29 Thread Terry Reedy

On 2/29/2016 8:22 AM, [email protected] wrote:

Hello Rustom,

F5 in Idle restarts the Python interpreter (that's what my impression is).


More exactly, IDLE runs user code in a separate process from the one 
that runs the IDLE gui.  Restarting means that the existing user process 
is terminated and a new one started.  This is easier than trying to 
'clean up' the existing process.


If you start python with '> python' in a terminal, then restarting the 
interactive interpreter means '>>> quit' at the interactive prompt 
followed by "> python" in the console.  You do the equivalent in IDLE 
Shell with 'control-F6' or 'Shell -> Restart Shell.


F5 when editing path/file.py replaces the command 'python' with 'cd 
path' followed by 'python -i file.py'


Maybe I should add something to the IDLE doc for people familiar with 
using python in a console.  (Most beginners are not.)



Whatever you have done earlier at Idle prompt (in Idle session)

> before F5 is gone after F5.

Yes, the same as if you quit().  A change I would like to make sometime 
is to have F5 run the file is a new user process without killing the old 
one, so one does not loose work done in Shell.


--
Terry Jan Reedy

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


Re: Condition fullfilled to early but only "sometimes"

2016-02-29 Thread Ian Kelly
It's not at all clear what the problem is from your description. What
is it that you expect the code to do? What is it doing instead that
violates your expectation? Why are you asking for Javascript help on a
Python mailing list?

On Mon, Feb 29, 2016 at 10:40 PM,   wrote:
> I've been looking at the code for two days so i am a bit crosseyed.
> If anyone could help me set the condition so the loop catch the last 
> pair/pairs, it is kind of weird that it succeed sometimes and break to early 
> and report fail others.
>
> I would be very greatful if anyone can see why it break to early and return 
> fail. Although it is clearly a succes looking at the last remaining pair none 
> connected pair.It should report fail for the network permutations that stall 
> due to link exhausting, but not stall creating last pair.
>
> It just a minor bug due to some condition that i just not get.
> Have a go 5 munutes maybe someone catch the faulthy condition.
>
> http://jt.node365.se/mydebug1.html
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sending an email with a binary attachment

2016-02-29 Thread Anthony Papillion
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA512

On 02/29/2016 11:13 AM, Chris Angelico wrote:
> On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson
>  wrote:
>> try: smtp.sendmail(message['From'], message['To'], 
>> message.as_string()) except: print "Message sending has failed" 
>> sys.exit(1) print "Message sending was successful" sys.exit(0)
>> 
> 
> This is the problem, right here. Replace this code with:
> 
> smtp.sendmail(message['From'], message['To'], message.as_string())

Hmm, I'm a bit confused. Are you saying that the problem is that I'm
enclosing the code in a Try/Except block? Besides that, I don't see
anything different. If it's the Try/Except block, how do I catch the
exception it might generate if I'm not using the exception block?

Thanks,
Anthony


-BEGIN PGP SIGNATURE-

iQIbBAEBCgAGBQJW1UuZAAoJEAKK33RTsEsVdfoP+N/xBIMouhhS1pqInvd9wrk2
jCfjmk7aHQQOdSvtQjXEqdNUu6nPmvX9VRzqvs881bUZAx31usL7VnyzJsL89pZl
PPrXG3WzEDkMaWmfZ45/irGwuP3Cpwkw3h7raDcvA/kV7+jLUBq//1kW7itofPh8
6xKJ9yCJ35vCS4LDhEeIbtMQXRe27QQXeFfi2VjFFRQRQeJlKf0nAd8sH/4q1fPa
IVKy6lgZcDDzCzy0Ux9us8baUOgTjLIY81AKMXGUmXaUNLpDfF6n6RLRtj8fLcN5
sT37okHyRmK9LNwI1PzU8r2p7i3gweDXx4x9g6nqmi6OV8fm4suSd8VOWb8oF1Yb
clQWSvSPE3GcnVaepcixIV1PCF53KsCHaPp63RZbKB3MiPuNTdQQi9Xm1Qfrt0UW
uJiEzfGXavkNRYaShycMB6HJGfjIsCZH9wzf1/irCuhiy+kJbvQq9lhojWw/V0N3
TGwY0Sd/eWqtmcx+u449viDIfLZsJDjzXXsYV60JdZtsSsd5+Mud+vfOlv3s/oy0
EPnIzMJar5LGPghPuab8g7rcXim77hFxS7eLp4j9ugWgRPa8TRpiBb/wx2c8a2e0
122ZW8Fc7+9gxHxSCJdM7GIFChdN2IMogCkERAuTyo+dNP01Mv07eMvSA6JkgiN2
ZlSJ8M9UHRS7dplpJGE=
=nxc8
-END PGP SIGNATURE-

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