Datetime string reformatting

2013-12-22 Thread Igor Korot
Hi, ALL,
I am trying to comprehend what is required to get a successful processing. ;-)
My script receives a data from the csv file. In this csv file there is
a datetime field.
This datetime field is formatted as follows: %m/%d/%Y
%H:%M:%S.{milliseconds}. I'm reading this field into the string with
this format.

The trouble comes from the fact that I need to insert this value into
mySQL. Doing it directly gives me an error: "Incorrect formatting".
After a bit of googling and trial I found out that mySQL is looking
for the format of '%Y/%m/%d %H:%M:%S.{milliseconds}.

There is a mySQL function which transfers the data into the proper
format: STR_TO_DATE(), but I can't obviously call it since it is not
known to Python.

Now obviously there should be a possibility to reformat this string.
I guess I can try to do:

mydate = date(mydate_from_csv)
text = mydate.format()

but this feels like an ugly hack.

Is there a better alternative?

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


Re: Datetime string reformatting

2013-12-22 Thread Mark Lawrence

On 22/12/2013 10:58, Igor Korot wrote:

Hi, ALL,
I am trying to comprehend what is required to get a successful processing. ;-)
My script receives a data from the csv file. In this csv file there is
a datetime field.
This datetime field is formatted as follows: %m/%d/%Y
%H:%M:%S.{milliseconds}. I'm reading this field into the string with
this format.

The trouble comes from the fact that I need to insert this value into
mySQL. Doing it directly gives me an error: "Incorrect formatting".
After a bit of googling and trial I found out that mySQL is looking
for the format of '%Y/%m/%d %H:%M:%S.{milliseconds}.

There is a mySQL function which transfers the data into the proper
format: STR_TO_DATE(), but I can't obviously call it since it is not
known to Python.

Now obviously there should be a possibility to reformat this string.
I guess I can try to do:

mydate = date(mydate_from_csv)
text = mydate.format()

but this feels like an ugly hack.

Is there a better alternative?

Thank you.



Round trip the data using these 
http://docs.python.org/3/library/datetime.html#strftime-strptime-behavior or 
use string slicing and dicing.


--
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


unicode to human readable format

2013-12-22 Thread tomasz . kaczorek
Hi,
i'm looking for solution the unicode string translation to the more readable 
format. 
I've got string like s=s=[u'\u0105\u017c\u0119\u0142\u0144'] and have no idea 
how to change to the human readable format. please help!

regards,
tomasz
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unicode to human readable format

2013-12-22 Thread Chris “Kwpolska” Warrick
On Sun, Dec 22, 2013 at 1:24 PM,   wrote:
> Hi,
> i'm looking for solution the unicode string translation to the more readable 
> format.
> I've got string like s=s=[u'\u0105\u017c\u0119\u0142\u0144'] and have no idea 
> how to change to the human readable format. please help!
>
> regards,
> tomasz
> --
> https://mail.python.org/mailman/listinfo/python-list

While printing the string, instead of the list/seeing the list’s repr,
Python shows a nice human-friendly representation.

>>> s=[u'\u0105\u017c\u0119\u0142\u0144']
>>> s
[u'\u0105\u017c\u0119\u0142\u0144']
>>> s[0]
u'\u0105\u017c\u0119\u0142\u0144'
>>> print s
[u'\u0105\u017c\u0119\u0142\u0144']
>>> print s[0]
ążęłń

However, that is only the case with Python 2, as Python 3 has a
human-friendly representation in the repr, too:

>>> s=[u'\u0105\u017c\u0119\u0142\u0144']
>>> s
['ążęłń']

-- 
Chris “Kwpolska” Warrick 
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unicode to human readable format

2013-12-22 Thread Peter Otten
tomasz.kaczo...@gmail.com wrote:

> Hi,
> i'm looking for solution the unicode string translation to the more
> readable format. I've got string like
> s=s=[u'\u0105\u017c\u0119\u0142\u0144'] and have no idea how to change to
> the human readable format. please help!

No, you have a list of strings:

>>> list_of_strings = [u'\u0105\u017c\u0119\u0142\u0144']
>>> print list_of_strings
[u'\u0105\u017c\u0119\u0142\u0144']

When a list is printed the individual items are converted to strings with 
repr() to avoid ambiguous output e. g. for strings with embeded commas.

If you want human readable strings print them individually instead of the 
whole list at once:

>>> for string in list_of_strings:
... print string
... 
ążęłń


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


vnc-problem with idle running as sudo on raspberry pi

2013-12-22 Thread Jean Dubois
I found the following solution to use idle on the raspberry pi
as sudoer (which is necessary or at least comfortable when programming the
GPIO) 
1. Open a terminal
2. type cd ~/Desktop
3. type touch idle_as_root
4. type nano idle_as_root
5. type in sudo idle
6. exit nano
7. type in sudo chmod +x idle_as_root
8. Close terminal
9. Double click on the idle_as_root program on your desktop

This all works fine as long as I use X, however
I also want to use it via vnc
For vnc I did the following:
Installed script "tightvncserver" on the RPiwith the following contents:
#!/bin/bash
# /etc/init.d/tightvncserver
VNCUSER='pi'
case "$1" in
   start)
#su $VNCUSER -c '/usr/bin/tightvncserver :1'
 su -l $VNCUSER -c '/usr/bin/tightvncserver :1'
 echo "Starting TightVNC server for $VNCUSER "
 ;;
   stop)
 pkill Xtightvnc
 echo "Tightvncserver stopped"
 ;;
   *)
 echo "Usage: /etc/init.d/tightvncserver {start|stop}"
 exit 1
 ;;
esac
exit 0 

sudo chmod 755 /etc/init.d/tightvncserver
sudo update-rc.d tightvncserver defaults

when starting the script manually like this
sudo /etc/init.d/tightvncserver start
everything works as expected i.e. I can click on the idle_as_root-icon and
it works as expected.
If however I reboot the system, the service does start and I do see the
rpi-desktop but clicking the idle_as_root-icon doesn't work. Manually
trying to start it as follows show an error:
pi@raspberrypi ~ $ sudo idle
Client is not authorized to connect to ServerTraceback (most recent call
last):
  File "/usr/bin/idle", line 5, in 
main()
  File "/usr/lib/python2.7/idlelib/PyShell.py", line 1427, in main
root = Tk(className="Idle")
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1712, in __init__
self.tk = _tkinter.create(screenName, baseName, className,
interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":1.0"


Does someone here have a solution for this problem?
thanks in advance
jean
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: vnc-problem with idle running as sudo on raspberry pi

2013-12-22 Thread Jean Dubois
Op zondag 22 december 2013 14:02:47 UTC+1 schreef Jean Dubois:
> I found the following solution to use idle on the raspberry pi
> as sudoer (which is necessary or at least comfortable when programming the
> GPIO) 
> 1. Open a terminal
> 2. type cd ~/Desktop
> 3. type touch idle_as_root
> 4. type nano idle_as_root
> 5. type in sudo idle
> 6. exit nano
> 7. type in sudo chmod +x idle_as_root
> 8. Close terminal
> 9. Double click on the idle_as_root program on your desktop
> This all works fine as long as I use X, however
> I also want to use it via vnc
> For vnc I did the following:
> Installed script "tightvncserver" on the RPiwith the following contents:
> #!/bin/bash
> # /etc/init.d/tightvncserver
> VNCUSER='pi'
> case "$1" in
>start)
> #su $VNCUSER -c '/usr/bin/tightvncserver :1'
>  su -l $VNCUSER -c '/usr/bin/tightvncserver :1'
>  echo "Starting TightVNC server for $VNCUSER "
>  ;;
>stop)
>  pkill Xtightvnc
>  echo "Tightvncserver stopped"
>  ;;
>*)
>  echo "Usage: /etc/init.d/tightvncserver {start|stop}"
>  exit 1
>  ;;
> esac
> exit 0 
> sudo chmod 755 /etc/init.d/tightvncserver
> sudo update-rc.d tightvncserver defaults
> when starting the script manually like this
> sudo /etc/init.d/tightvncserver start
> everything works as expected i.e. I can click on the idle_as_root-icon and
> it works as expected.
I was wrong writing idle_as_root worked this way. As a matter of fact,
this method also does not work as expected, as can be seen from this
message:

X11 connection rejected because of wrong authentication.

New 'X' desktop is raspberrypi:1

Starting applications specified in /home/pi/.vnc/xstartup
Log file is /home/pi/.vnc/raspberrypi:1.log

Starting TightVNC server for pi 




> If however I reboot the system, the service does start and I do see the
> rpi-desktop but clicking the idle_as_root-icon doesn't work. Manually
> trying to start it as follows show an error:
> pi@raspberrypi ~ $ sudo idle
> Client is not authorized to connect to ServerTraceback (most recent call
> last):
>   File "/usr/bin/idle", line 5, in 
> main()
>   File "/usr/lib/python2.7/idlelib/PyShell.py", line 1427, in main
> root = Tk(className="Idle")
>   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1712, in __init__
> self.tk = _tkinter.create(screenName, baseName, className,
> interactive, wantobjects, useTk, sync, use)
> _tkinter.TclError: couldn't connect to display ":1.0"

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


Re: [OT] vnc-problem with idle running as sudo on raspberry pi

2013-12-22 Thread Michael Torrie
On 12/22/2013 06:27 AM, Jean Dubois wrote:
> I was wrong writing idle_as_root worked this way. As a matter of fact,
> this method also does not work as expected, as can be seen from this
> message:
> 
> X11 connection rejected because of wrong authentication.
> 
> New 'X' desktop is raspberrypi:1
> 
> Starting applications specified in /home/pi/.vnc/xstartup
> Log file is /home/pi/.vnc/raspberrypi:1.log
> 
> Starting TightVNC server for pi 

In future, I suspect you'll need to take questions like this that don't
really have anything to do with Python to a Raspberry Pi forum or e-mail
list.  Or a general Linux list.

Short answer:

Edit /etc/sudoers and add this line somewhere in it (probably near other
lines that look similar):

Defaults env_keep += "DISPLAY XAUTHORITY"

If that doesn't work, then you'll have to talk to folks running the
Rasbian on their Pi.  Sometimes XAUTHORITY isn't set.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Datetime string reformatting

2013-12-22 Thread Andreas Perstinger

On 22.12.2013 11:58, Igor Korot wrote:

My script receives a data from the csv file. In this csv file there is
a datetime field.
This datetime field is formatted as follows: %m/%d/%Y
%H:%M:%S.{milliseconds}. I'm reading this field into the string with
this format.

The trouble comes from the fact that I need to insert this value into
mySQL. Doing it directly gives me an error: "Incorrect formatting".
After a bit of googling and trial I found out that mySQL is looking
for the format of '%Y/%m/%d %H:%M:%S.{milliseconds}.

There is a mySQL function which transfers the data into the proper
format: STR_TO_DATE(), but I can't obviously call it since it is not
known to Python.


You don't want to call "STR_TO_DATE()" from Python but use it inside the 
SQL statement.


So instead of doing the conversion in Python as Mark suggested, you 
could do something like


sql_stmt = """INSERT ...
  VALUES (..., STR_TO_DATE(%s, "%m/%d/%Y %H:%M:%S.{%f}"),
  ...)"""
cursor.execute(sql_stmt, (..., mydate_from_csv, ...))

(BTW: Do you mean microseconds instead of milliseconds? And are the 
"milliseconds" really inside curly braces?)


Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread em rexhepi
I know is my fault i'm no good programmer, I'm a begginer that's why i need 
your help.

I have a python 3.3 project to be finished. I did what i could there is not 
much help on google about this topic.

The project is to load a webpage from any website and filter the ads.
I'm using ABPY library to filter, here is the link:
https://github.com/atereshkin/abpy <- needs to be converted in python 3.x it is 
on 2.x
easylist.txt link: https://easylist-downloads.adblockplus.org/easylist.txt


When I use my code it just displays nothing

My code:
#!/usr/local/bin/python3.1

import cgitb;cgitb.enable()

import urllib.request
response = urllib.request.build_opener()
response.addheaders = [('User-agent', 'Mozilla/5.0')]
response = urllib.request.urlopen("www.youtube.com";)

html = response.read()

from abpy import Filter
with open("easylist.txt") as f:
f = Filter(file('easylist.txt'))
f.match(html)


print("Content-type: text/html")
print()
print (html)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 4:20 AM, em rexhepi  wrote:
> I have a python 3.3 project to be finished. ...
>
> My code:
> #!/usr/local/bin/python3.1

Your shebang says 3.1, are you sure that's correct? Maybe it's not
finding the right interpreter.

If this is running as CGI, which it seems to be, check your server
error logs. It's quite possible you're getting back a blank page
because something's bombing, in which case - if you're lucky -
there'll be a full exception traceback in the log.

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


Getting updates and restarting a long running url request.

2013-12-22 Thread Vincent Davis
I am using biopython's NCBIWWW.qblast which sends a request to the ncbi
website and waits for a result. The relevant code can be found at the link
below starting at about 151. Basically it is a while loop waiting for the
blast query.
http://biopython.org/DIST/docs/api/Bio.Blast.NCBIWWW-pysrc.html

My problem; I am submitting about 75 request (one at a time and with
delays) and they can each take minutes to complete. I think sometimes the
request/response/query fails which results in me needing to restart
the process.

I am looking for suggestion on how to monitor and restart the process if I
think it has failed.

I am using the following code to submit the query/
def get_BLAST(taxid, queryseq, args=None):
'''
Input taxid to BLAST queryseq against
'''
e_query = "txid" + taxid + " [ORGN]"
#, other_advanced='-G 4 -E 1'
blast_result = NCBIWWW.qblast("blastn", "nt", queryseq, megablast=True,
entrez_query=e_query, word_size='11', other_advanced='-G 5 -E 2')
return NCBIXML.read(blast_result)


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


Re: BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread Michael Torrie
On 12/22/2013 10:20 AM, em rexhepi wrote:
> When I use my code it just displays nothing
> 
> My code:
> #!/usr/local/bin/python3.1
> 
> import cgitb;cgitb.enable()
> 
> import urllib.request
> response = urllib.request.build_opener()
> response.addheaders = [('User-agent', 'Mozilla/5.0')]
> response = urllib.request.urlopen("www.youtube.com";)
> 
> html = response.read()
> 
> from abpy import Filter
> with open("easylist.txt") as f:
> f = Filter(file('easylist.txt'))
> f.match(html)

What happens when you comment out the above four lines?  Does the web
page print without the filtering?  Just as a sanity check.  My hunch is
that html has no data in it.

Also what is "f.match(html)" supposed to return? Is it supposed to
mutate html (seems unlikely) or does it return something? Looking at the
source code, match() does not return anything, but prints to stdout,
which is weird, but at least that tells us that it doesn't actually
change the html object.

> print("Content-type: text/html")
> print()
> print (html)

I'm not sure you're doing this right.  adpy seems a bit goofy, but since
f.match() does not appear to change html at all, you should get the same
html out that urllib grabbed.  So if you're not getting any output, that
means you're not getting the original html somehow.  Also if f.match()
is doing its thing, I don't think you want to print out html after the
command, because f.match itself is printing to stdout itself.

Have you looked over the adpy source code?  I haven't bothered to run
it, but a glance through the code would seem to indicate that it doesn't
actually do the filtering at all, but rather just prints out the rules
that the html code you provide would match.  I bet you could modify it
to do filtering though.  Maybe add a method that uses rule.sub to
replace the bad text with an empty string.

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


Re: BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread Mark Lawrence

On 22/12/2013 17:20, em rexhepi wrote:

I know is my fault i'm no good programmer, I'm a begginer that's why i need 
your help.

I have a python 3.3 project to be finished. I did what i could there is not 
much help on google about this topic.

The project is to load a webpage from any website and filter the ads.
I'm using ABPY library to filter, here is the link:
https://github.com/atereshkin/abpy <- needs to be converted in python 3.x it is 
on 2.x
easylist.txt link: https://easylist-downloads.adblockplus.org/easylist.txt


When I use my code it just displays nothing

My code:
#!/usr/local/bin/python3.1

import cgitb;cgitb.enable()

import urllib.request
response = urllib.request.build_opener()
response.addheaders = [('User-agent', 'Mozilla/5.0')]
response = urllib.request.urlopen("www.youtube.com";)

html = response.read()

from abpy import Filter
with open("easylist.txt") as f:
f = Filter(file('easylist.txt'))
f.match(html)


Whats the above meant to be doing?  You've opened easylist.txt as f and 
then reassigned f, passing easylist.txt to file which doesn't exist in 
Python 3.





print("Content-type: text/html")
print()
print (html)




--
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


Error while building Python doc

2013-12-22 Thread shankha
Hi,
I am trying to build Python documents as listed here

http://docs.python.org/devguide/documenting.html#building-the-documentation

make -C Doc html

Error message:
Checked out revision 89010.
mkdir -p build/html build/doctrees
python tools/sphinx-build.py -b html -d build/doctrees -D
latex_paper_size=  . build/html
Traceback (most recent call last):
  File "tools/sphinx-build.py", line 27, in 
from sphinx import main
ImportError: No module named sphinx
make: *** [build] Error 1
make: Leaving directory `Python-git/cpythonL-doc/Doc'


Sphinx is located inside the directory:

Doc/tools.

Do I need to change how I import (the path may be).

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


cascading python executions only if return code is 0

2013-12-22 Thread Frank Cui
hey guys,
I have a requirement where I need to sequentially execute a bunch of 
executions, each execution has a return code. the followed executions should 
only be executed if the return code is 0. is there a cleaner or more pythonic 
way to do this other than the following ? 
if a() == 0:if b() == 0:c()
Thanks for your input.
frank -- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Roy Smith
In article ,
 Frank Cui  wrote:

> hey guys,
> I have a requirement where I need to sequentially execute a bunch of 
> executions, each execution has a return code. the followed executions should 
> only be executed if the return code is 0. is there a cleaner or more pythonic 
> way to do this other than the following ? 
> if a() == 0:if b() == 0:c()
> Thanks for your input.
> frank   

Yup!  Just do:

a() or b() or c()

The "or" operation has what's known as "short-circuit" semantics.  That 
means, if the first operand is true, it doesn't evaluate the second 
operand.  Just make sure that a(), b(), and c() all return something 
which is true if they succeed and false otherwise.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Peter Otten
Frank Cui wrote:

> hey guys,
> I have a requirement where I need to sequentially execute a bunch of
> executions, each execution has a return code. the followed executions
> should only be executed if the return code is 0. is there a cleaner or
> more pythonic way to do this other than the following ?
> if a() == 0:if b() == 0:c()
> Thanks for your input.
> frank

funcs = a, b, c

# option 1
for f in funcs:
if f():
break

# option 2
any(f() for f in funcs)


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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Gary Herron

On 12/22/2013 10:37 AM, Frank Cui wrote:

hey guys,

I have a requirement where I need to sequentially execute a bunch of 
executions, each execution has a return code. the followed executions 
should only be executed if the return code is 0. is there a cleaner or 
more pythonic way to do this other than the following ?


if a() == 0:
if b() == 0:
c()

Thanks for your input.

frank


This would seem to do the same as your code and could easily be extended 
to your "bunch" of things:


exes = [a, b, c]

for e in exes:
  if e() != 0:
break
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: cascading python executions only if return code is 0

2013-12-22 Thread Frank Cui
Thanks, this looks beautiful
> To: python-list@python.org
> From: __pete...@web.de
> Subject: Re: cascading python executions only if return code is 0
> Date: Sun, 22 Dec 2013 20:26:15 +0100
> 
> Frank Cui wrote:
> 
> > hey guys,
> > I have a requirement where I need to sequentially execute a bunch of
> > executions, each execution has a return code. the followed executions
> > should only be executed if the return code is 0. is there a cleaner or
> > more pythonic way to do this other than the following ?
> > if a() == 0:if b() == 0:c()
> > Thanks for your input.
> > frank
> 
> funcs = a, b, c
> 
> # option 1
> for f in funcs:
> if f():
> break
> 
> # option 2
> any(f() for f in funcs)
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list
  -- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Mark Lawrence

On 22/12/2013 19:17, Roy Smith wrote:

In article ,
  Frank Cui  wrote:


hey guys,
I have a requirement where I need to sequentially execute a bunch of
executions, each execution has a return code. the followed executions should
only be executed if the return code is 0. is there a cleaner or more pythonic
way to do this other than the following ?
if a() == 0:if b() == 0:c()
Thanks for your input.
frank   


Yup!  Just do:

a() or b() or c()

The "or" operation has what's known as "short-circuit" semantics.  That
means, if the first operand is true, it doesn't evaluate the second
operand.  Just make sure that a(), b(), and c() all return something
which is true if they succeed and false otherwise.



Really? :)

--
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: cascading python executions only if return code is 0

2013-12-22 Thread Frank Cui
sorry, but what if I need to have different parameters in these functions ?

> To: python-list@python.org
> From: breamore...@yahoo.co.uk
> Subject: Re: cascading python executions only if return code is 0
> Date: Sun, 22 Dec 2013 19:31:21 +
> 
> On 22/12/2013 19:17, Roy Smith wrote:
> > In article ,
> >   Frank Cui  wrote:
> >
> >> hey guys,
> >> I have a requirement where I need to sequentially execute a bunch of
> >> executions, each execution has a return code. the followed executions 
> >> should
> >> only be executed if the return code is 0. is there a cleaner or more 
> >> pythonic
> >> way to do this other than the following ?
> >> if a() == 0:if b() == 0:c()
> >> Thanks for your input.
> >> frank  
> >
> > Yup!  Just do:
> >
> > a() or b() or c()
> >
> > The "or" operation has what's known as "short-circuit" semantics.  That
> > means, if the first operand is true, it doesn't evaluate the second
> > operand.  Just make sure that a(), b(), and c() all return something
> > which is true if they succeed and false otherwise.
> >
> 
> Really? :)
> 
> -- 
> 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
  -- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Ned Batchelder

On 12/22/13 2:10 PM, Frank Cui wrote:

sorry, but what if I need to have different parameters in these functions ?


Frank, welcome to the group.  Common convention is to put your response 
below the exiting message, so that the conversation continues down the page.


(See my answer below... :)




 > To: python-list@python.org
 > From: breamore...@yahoo.co.uk
 > Subject: Re: cascading python executions only if return code is 0
 > Date: Sun, 22 Dec 2013 19:31:21 +
 >
 > On 22/12/2013 19:17, Roy Smith wrote:
 > > In article ,
 > > Frank Cui  wrote:
 > >
 > >> hey guys,
 > >> I have a requirement where I need to sequentially execute a bunch of
 > >> executions, each execution has a return code. the followed
executions should
 > >> only be executed if the return code is 0. is there a cleaner or
more pythonic
 > >> way to do this other than the following ?
 > >> if a() == 0: if b() == 0: c()
 > >> Thanks for your input.
 > >> frank
 > >
 > > Yup! Just do:
 > >
 > > a() or b() or c()
 > >
 > > The "or" operation has what's known as "short-circuit" semantics. That
 > > means, if the first operand is true, it doesn't evaluate the second
 > > operand. Just make sure that a(), b(), and c() all return something
 > > which is true if they succeed and false otherwise.
 > >
 >
 > Really? :)
 >
 > --
 > 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




The most Python-natural way to deal with your problem would be to have 
these functions not return status codes at all.  Instead, have them 
raise an exception if something goes wrong.   Then you can invoke them 
most naturally:


a()
b()
c()

Execution will continue as long as no exceptions are raised.  If you 
need to deal with the failure case also, then:


try:
a()
b()
c()
except Exception as e:
# do something here

Depending on how you want to deal with failures, you'd probably use your 
own subclass of Exception, but this is the general idea.


Return codes can be awkward, especially in Python which has exception 
integrated so fully into the language, library, and culture.


--
Ned Batchelder, http://nedbatchelder.com

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


RE: cascading python executions only if return code is 0

2013-12-22 Thread Frank Cui


> To: python-list@python.org
> From: n...@nedbatchelder.com
> Subject: Re: cascading python executions only if return code is 0
> Date: Sun, 22 Dec 2013 14:49:43 -0500
> 
> On 12/22/13 2:10 PM, Frank Cui wrote:
> > sorry, but what if I need to have different parameters in these functions ?
> 
> Frank, welcome to the group.  Common convention is to put your response 
> below the exiting message, so that the conversation continues down the page.
> 
> (See my answer below... :)
> 
> >
> >
> >  > To: python-list@python.org
> >  > From: breamore...@yahoo.co.uk
> >  > Subject: Re: cascading python executions only if return code is 0
> >  > Date: Sun, 22 Dec 2013 19:31:21 +
> >  >
> >  > On 22/12/2013 19:17, Roy Smith wrote:
> >  > > In article ,
> >  > > Frank Cui  wrote:
> >  > >
> >  > >> hey guys,
> >  > >> I have a requirement where I need to sequentially execute a bunch of
> >  > >> executions, each execution has a return code. the followed
> > executions should
> >  > >> only be executed if the return code is 0. is there a cleaner or
> > more pythonic
> >  > >> way to do this other than the following ?
> >  > >> if a() == 0: if b() == 0: c()
> >  > >> Thanks for your input.
> >  > >> frank
> >  > >
> >  > > Yup! Just do:
> >  > >
> >  > > a() or b() or c()
> >  > >
> >  > > The "or" operation has what's known as "short-circuit" semantics. That
> >  > > means, if the first operand is true, it doesn't evaluate the second
> >  > > operand. Just make sure that a(), b(), and c() all return something
> >  > > which is true if they succeed and false otherwise.
> >  > >
> >  >
> >  > Really? :)
> >  >
> >  > --
> >  > 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
> >
> >
> 
> The most Python-natural way to deal with your problem would be to have 
> these functions not return status codes at all.  Instead, have them 
> raise an exception if something goes wrong.   Then you can invoke them 
> most naturally:
> 
>  a()
>  b()
>  c()
> 
> Execution will continue as long as no exceptions are raised.  If you 
> need to deal with the failure case also, then:
> 
>  try:
>  a()
>  b()
>  c()
>  except Exception as e:
>  # do something here
> 
> Depending on how you want to deal with failures, you'd probably use your 
> own subclass of Exception, but this is the general idea.
> 
> Return codes can be awkward, especially in Python which has exception 
> integrated so fully into the language, library, and culture.
> 
> -- 
> Ned Batchelder, http://nedbatchelder.com
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Thanks for informing the rules.   -- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Roy Smith
In article ,
 Mark Lawrence  wrote:

> On 22/12/2013 19:17, Roy Smith wrote:
> > In article ,
> >   Frank Cui  wrote:
> >
> >> hey guys,
> >> I have a requirement where I need to sequentially execute a bunch of
> >> executions, each execution has a return code. the followed executions 
> >> should
> >> only be executed if the return code is 0. is there a cleaner or more 
> >> pythonic
> >> way to do this other than the following ?
> >> if a() == 0:if b() == 0:c()
> >> Thanks for your input.
> >> frank  
> >
> > Yup!  Just do:
> >
> > a() or b() or c()
> >
> > The "or" operation has what's known as "short-circuit" semantics.  That
> > means, if the first operand is true, it doesn't evaluate the second
> > operand.  Just make sure that a(), b(), and c() all return something
> > which is true if they succeed and false otherwise.
> >
> 
> Really? :)

I believe what Mark is so elegantly trying to say is, "Roy is a dufus 
and got that backwards".  You need to return something which is false to 
make the next one in the chain get executed.

$ cat or.py 
def a():
print "a"
return 0

def b():
print "b"
return 1

def c():
print "c"
return 0

a() or b() or c()


$ python or.py
a
b
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread MRAB

On 22/12/2013 18:08, Michael Torrie wrote:

On 12/22/2013 10:20 AM, em rexhepi wrote:

When I use my code it just displays nothing

My code:
#!/usr/local/bin/python3.1

import cgitb;cgitb.enable()

import urllib.request
response = urllib.request.build_opener()
response.addheaders = [('User-agent', 'Mozilla/5.0')]
response = urllib.request.urlopen("www.youtube.com";)

html = response.read()

from abpy import Filter
with open("easylist.txt") as f:
f = Filter(file('easylist.txt'))
f.match(html)


What happens when you comment out the above four lines?  Does the web
page print without the filtering?  Just as a sanity check.  My hunch is
that html has no data in it.

Also what is "f.match(html)" supposed to return? Is it supposed to
mutate html (seems unlikely) or does it return something? Looking at the
source code, match() does not return anything, but prints to stdout,
which is weird, but at least that tells us that it doesn't actually
change the html object.


print("Content-type: text/html")
print()
print (html)


I'm not sure you're doing this right.  adpy seems a bit goofy, but since
f.match() does not appear to change html at all, you should get the same
html out that urllib grabbed.  So if you're not getting any output, that
means you're not getting the original html somehow.  Also if f.match()
is doing its thing, I don't think you want to print out html after the
command, because f.match itself is printing to stdout itself.

Have you looked over the adpy source code?  I haven't bothered to run
it, but a glance through the code would seem to indicate that it doesn't
actually do the filtering at all, but rather just prints out the rules
that the html code you provide would match.  I bet you could modify it
to do filtering though.  Maybe add a method that uses rule.sub to
replace the bad text with an empty string.


The urlopen call also contains a stray semicolon.

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


Re: Error while building Python doc

2013-12-22 Thread Terry Reedy

On 12/22/2013 1:53 PM, shankha wrote:

Hi,
I am trying to build Python documents as listed here

http://docs.python.org/devguide/documenting.html#building-the-documentation

make -C Doc html

Error message:
Checked out revision 89010.
mkdir -p build/html build/doctrees
python tools/sphinx-build.py -b html -d build/doctrees -D
latex_paper_size=  . build/html
Traceback (most recent call last):
   File "tools/sphinx-build.py", line 27, in 
 from sphinx import main
ImportError: No module named sphinx
make: *** [build] Error 1
make: Leaving directory `Python-git/cpythonL-doc/Doc'

Sphinx is located inside the directory: Doc/tools.


Based on my Windows tree, that should be Doc/tools/sphinx/, along with 
docutils, jinja, and pygments directories. To be a module, sphinx must 
contain __init__.py, along with other files.



Do I need to change how I import (the path may be).


Did you run "make -C Doc checkout" first? (I do not know what the -C 
does, as I just do "make checkout" and occasionally make update in Doc 
on Windows, which run Doc/make.bat.


--
Terry Jan Reedy

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


Re: BLANK PAGE when i try Filtering Adsense with abpy

2013-12-22 Thread Terry Reedy

On 12/22/2013 12:20 PM, em rexhepi wrote:

I know is my fault i'm no good programmer, I'm a begginer that's why i need 
your help.

I have a python 3.3 project to be finished. I did what i could there is not 
much help on google about this topic.

The project is to load a webpage from any website and filter the ads.
I'm using ABPY library to filter, here is the link:
https://github.com/atereshkin/abpy <- needs to be converted in python 3.x it is 
on 2.x
easylist.txt link: https://easylist-downloads.adblockplus.org/easylist.txt


When I use my code it just displays nothing

My code:
#!/usr/local/bin/python3.1


Please update your Python 3 if you are not in a straightjacket 
preventing you from doing so.



import cgitb;cgitb.enable()


I suggest commenting this out and running normally in a console or Idle 
so you are guaranteed to see output, including error tracebacks. Only 
use cgi when this runs successfully in normal mode.



import urllib.request
response = urllib.request.build_opener()
response.addheaders = [('User-agent', 'Mozilla/5.0')]
response = urllib.request.urlopen("www.youtube.com";)


The ; is a SyntaxError and Python exits. See above.



html = response.read()

from abpy import Filter
with open("easylist.txt") as f:
f = Filter(file('easylist.txt'))
f.match(html)


print("Content-type: text/html")
print()
print (html)




--
Terry Jan Reedy

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


Re: Error while building Python doc

2013-12-22 Thread Christian Heimes
Am 22.12.2013 21:59, schrieb Terry Reedy:
> Did you run "make -C Doc checkout" first? (I do not know what the -C
> does, as I just do "make checkout" and occasionally make update in Doc
> on Windows, which run Doc/make.bat.

-C == change directory

"make -C Doc html" is like "cd Doc; make html; cd .."

Christian


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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Cameron Simpson
On 22Dec2013 15:05, Roy Smith  wrote:
> In article ,
>  Mark Lawrence  wrote:
> 
> > On 22/12/2013 19:17, Roy Smith wrote:
> > > In article ,
> > >   Frank Cui  wrote:
> > >> I have a requirement where I need to sequentially execute a bunch of
> > >> executions, each execution has a return code. the followed executions 
> > >> should
> > >> only be executed if the return code is 0. is there a cleaner or more 
> > >> pythonic
> > >> way to do this other than the following ?
> > >> if a() == 0:if b() == 0:c()
> > >
> > > Yup!  Just do:
> > >
> > > a() or b() or c()
> > >
> > > The "or" operation has what's known as "short-circuit" semantics.  That
> > > means, if the first operand is true, it doesn't evaluate the second
> > > operand.  Just make sure that a(), b(), and c() all return something
> > > which is true if they succeed and false otherwise.
> > 
> > Really? :)
> 
> I believe what Mark is so elegantly trying to say is, "Roy is a dufus 
> and got that backwards".  You need to return something which is false to 
> make the next one in the chain get executed.
> 
> $ cat or.py 
> def a():
> print "a"
> return 0
> 
> def b():
> print "b"
> return 1
> 
> def c():
> print "c"
> return 0
> 
> a() or b() or c()
> 
> 
> $ python or.py
> a
> b

Yeah.

Roy's code _depends_ upon the return value being equivalent to False.

A better approach would be:

  a() == 0 and b() == 1 and c() == 0

i.e. to explicitly check each return code against the expected/desired
value instead of relying on some flukey coincidental property of
the (arbitrary) numeric value returned.

Better still is the suggestion elsewhere in the thread to make the functions
raise exceptions on error instead of returning a number.

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Roy Smith
In article ,
 Cameron Simpson  wrote:

> Roy's code _depends_ upon the return value being equivalent to False.

Yes.  You view this as a flaw.  I view it as a feature :-)

> A better approach would be:
> 
>   a() == 0 and b() == 1 and c() == 0
> 
> i.e. to explicitly check each return code against the expected/desired
> value instead of relying on some flukey coincidental property of
> the (arbitrary) numeric value returned.

You're assuming it's arbitrary.  I'm saying do it that way by design.  

> Better still is the suggestion elsewhere in the thread to make the functions
> raise exceptions on error instead of returning a number.

Possibly.  But, I think of exceptions as indicating that something went 
wrong.  There's two possible things the OP was trying to do here:

1) He intends that all of the functions get run, but each one can only 
get run if all the ones before it succeed.  In that case, I agree that 
the exception pattern makes sense.

2) He intends that each of the functions gets tried, and the first one 
that can return a value wins.  If that's the case, the "or" chaining 
seems more natural.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Cameron Simpson
On 22Dec2013 16:53, Roy Smith  wrote:
> In article ,
>  Cameron Simpson  wrote:
> > Roy's code _depends_ upon the return value being equivalent to False.
> 
> Yes.  You view this as a flaw.  I view it as a feature :-)

When I write functions which return a boolean indicating success/failure,
I try to make that boolean be "true" for success.

Now, I do take the point that these functions seem to take the
unix-exit-code convention that zero is success (leaving the many
values of "non-zero" to indicate flavours of failure as desired,
as we have many types of exceptions).

Or, possibly, that a non-zero return indicates the number of errors
encountered; I do that myself for things like option or file parsing,
where I explicitly want to parse of much of a command line (or
whatever) as possible before rejecting things; few things annoy me
as much as a command that barfs about the first usage error and
aborts instead of barfing multiple times and aborting. Unless it
is a command that does the same and then fails to recite a usage
message after the barf. (Yes, almost every GNU command on the planet:
I'm looking at you!)

However, in this count-of-errors scenario I tend to try to return
a list of errors, not a count.

But regardless, I consider code that goes:

  a() or b() or c()

as a test for _success_ of a(), b() and c() in succession to be
misleading at best. When I write that above incantation it is a
test for failure: try this, or try that, or finally try this other
thing.

> > A better approach would be:
> > 
> >   a() == 0 and b() == 1 and c() == 0
> > 
> > i.e. to explicitly check each return code against the expected/desired
> > value instead of relying on some flukey coincidental property of
> > the (arbitrary) numeric value returned.
> 
> You're assuming it's arbitrary.  I'm saying do it that way by design.  

The counter example the above is based upon deliberately returned
1 for success from b(), IIRC. Different design.

The OP was unclear about his/her design rationale.

> > Better still is the suggestion elsewhere in the thread to make the functions
> > raise exceptions on error instead of returning a number.
> 
> Possibly.  But, I think of exceptions as indicating that something went 
> wrong.

I think of failure as "something went wrong".
Yes, I'll grant there are shades of intent here.

> There's two possible things the OP was trying to do here:
> 
> 1) He intends that all of the functions get run, but each one can only 
> get run if all the ones before it succeed.  In that case, I agree that 
> the exception pattern makes sense.

His cascading if-statement in the OP suggested this to me.

> 2) He intends that each of the functions gets tried, and the first one 
> that can return a value wins.  If that's the case, the "or" chaining 
> seems more natural.

I'm pretty sure that wasn't his intent, again based on my recollection
of the OP. But I still dislike "a() or b() or c()" as a test for
chained success; I think it is a bad idiom.

Cheers,
-- 
Cameron Simpson 

I must construct my own System, or be enslaved to another Man's.
- William Blake
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Rick Johnson
On Sunday, December 22, 2013 12:37:04 PM UTC-6, Frank Cui wrote:
> I have a requirement where I need to sequentially execute
> a bunch of executions, each execution has a return code.
> the followed executions should only be executed if the
> return code is 0. is there a cleaner or more pythonic way
> to do this other than the following ?
>
> if a() == 0:
> if b() == 0:
> c()

Hello Frank.

I kindly request that you be more specific when asking
questions. Both your question and your example code contain
too many ambiguities.

I'm still not sure what exact outcome you wish to achieve,
the only certainty is that you wish to perform a linear
execution of "N" members with later executions being affected
by earlier executions.

Whether you want executions to proceed on failure or proceed
on success is unclear. Here are a few explicit pseudo code
examples that would have removed all ambiguities:

if fails(a()):
if fails(b()):
c()

if succeeds(a()):
if succeeds(b()):
c()

Or if you prefer a purely OOP approach:

a.foo()
b.foo()
if a.failed:
if b.failed:
c.foo()

a.foo()
b.foo()
if a.succeeded:
if b.succeeded:
c.foo()

or you could simplify using a logical one liner:

if !a() and !b() then c()
if a() and b() then c()

Of course you could use the "all" function

if all(a(), b()):
c()
if not any(a(), b()):
c()

But this "all" depends whether you're testing for success or
testing for failure, and that point is a distant third from
my desperate need of understanding your semantics of "what"
values are *true* and "what" values are *false*.

I think (sadly) more time is spent attempting to interpret
what an OP is asking rather than attempting to provide a
solution to the problem the OP is suffering, and whilst any
problem solving adventure is likely to improve our
intelligence, fumbling about attempting to decode
ambiguities is indeed time that could have been better spent
IF ONLY the speaker (or writer) had put a small bit more
effort into the question.

Look Frank, nobody is perfect, we all need to improve our
skills here or there. So don't be offended that my
statements are, well,... "frank".


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


RE: cascading python executions only if return code is 0

2013-12-22 Thread Frank Cui


> Date: Sun, 22 Dec 2013 14:27:35 -0800
> Subject: Re: cascading python executions only if return code is 0
> From: rantingrickjohn...@gmail.com
> To: python-list@python.org
> 
> On Sunday, December 22, 2013 12:37:04 PM UTC-6, Frank Cui wrote:
> > I have a requirement where I need to sequentially execute
> > a bunch of executions, each execution has a return code.
> > the followed executions should only be executed if the
> > return code is 0. is there a cleaner or more pythonic way
> > to do this other than the following ?
> >
> > if a() == 0:
> > if b() == 0:
> > c()
> 
> Hello Frank.
> 
> I kindly request that you be more specific when asking
> questions. Both your question and your example code contain
> too many ambiguities.
> 
> I'm still not sure what exact outcome you wish to achieve,
> the only certainty is that you wish to perform a linear
> execution of "N" members with later executions being affected
> by earlier executions.
> 
> Whether you want executions to proceed on failure or proceed
> on success is unclear. Here are a few explicit pseudo code
> examples that would have removed all ambiguities:
> 
> if fails(a()):
> if fails(b()):
> c()
> 
> if succeeds(a()):
> if succeeds(b()):
> c()
> 
> Or if you prefer a purely OOP approach:
> 
> a.foo()
> b.foo()
> if a.failed:
> if b.failed:
> c.foo()
> 
> a.foo()
> b.foo()
> if a.succeeded:
> if b.succeeded:
> c.foo()
> 
> or you could simplify using a logical one liner:
> 
> if !a() and !b() then c()
> if a() and b() then c()
> 
> Of course you could use the "all" function
> 
> if all(a(), b()):
> c()
> if not any(a(), b()):
> c()
> 
> But this "all" depends whether you're testing for success or
> testing for failure, and that point is a distant third from
> my desperate need of understanding your semantics of "what"
> values are *true* and "what" values are *false*.
> 
> I think (sadly) more time is spent attempting to interpret
> what an OP is asking rather than attempting to provide a
> solution to the problem the OP is suffering, and whilst any
> problem solving adventure is likely to improve our
> intelligence, fumbling about attempting to decode
> ambiguities is indeed time that could have been better spent
> IF ONLY the speaker (or writer) had put a small bit more
> effort into the question.
> 
> Look Frank, nobody is perfect, we all need to improve our
> skills here or there. So don't be offended that my
> statements are, well,... "frank".
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Hi Rick,
Thanks for pointing out. I accept your advice and will try to make the 
questions clearer and more straightforward to interpretate . I already took the 
suggestion of using exception-based handling over the return code.
As to testing whether the previous function fails or succeeds, this doesn't 
really matter in the sense that I already mentioned a return code of 0. 
ThanksFrank 

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 9:14 AM, Frank Cui  wrote:
> Thanks for pointing out. I accept your advice and will try to make the
> questions clearer and more straightforward to interpretate . I already took
> the suggestion of using exception-based handling over the return code.
>
> As to testing whether the previous function fails or succeeds, this doesn't
> really matter in the sense that I already mentioned a return code of 0.

Ranting Rick is one of the list's resident trolls. Don't take it amiss
that he turned his flamethrowers on you. :)

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Mark Lawrence

On 22/12/2013 22:51, Chris Angelico wrote:

On Mon, Dec 23, 2013 at 9:14 AM, Frank Cui  wrote:

Thanks for pointing out. I accept your advice and will try to make the
questions clearer and more straightforward to interpretate . I already took
the suggestion of using exception-based handling over the return code.

As to testing whether the previous function fails or succeeds, this doesn't
really matter in the sense that I already mentioned a return code of 0.


Ranting Rick is one of the list's resident trolls. Don't take it amiss
that he turned his flamethrowers on you. :)

ChrisA



Given that Frank originally stated this

"
I have a requirement where I need to sequentially execute a bunch of 
executions, each execution has a return code. the followed executions 
should only be executed if the return code is 0. is there a cleaner or 
more pythonic way to do this other than the following ?


if a() == 0:
if b() == 0:
c()
"

I can only see one way that you can possibly intepret it.  Perhaps rr 
was dashing off a reply on a mobile device while doing a home run, hence 
wasn't concentrating on what Frank had actually said?


--
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: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Bob Rashkin
On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:
> basically what I wanna do is this :
> 
> 
> 
> x = 4
> 
> y = 7
> 
> def switch (z,w):
> 
> ***this will switch z to w and vice verca***
> 
>  c= z
> 
>  z=w
> 
>  w=c
> 
>  print 'Now x =', w, 'and y = ' , z
> 
>  return w
> 
> x = switch(x,y)
> 
> 
> 
>  How am I supposed to do so I can  return also a value to the variable y 
> WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?
> 
> 
> 
> thanks in advance

Not sure I understand the problem but I think the answer is to put multiple 
values in a list and return the list.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Joel Goldstick
return a tuple:

return a, b, c

or whatever


On Sun, Dec 22, 2013 at 6:41 PM, Bob Rashkin  wrote:

> On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:
> > basically what I wanna do is this :
> >
> >
> >
> > x = 4
> >
> > y = 7
> >
> > def switch (z,w):
> >
> > ***this will switch z to w and vice verca***
> >
> >  c= z
> >
> >  z=w
> >
> >  w=c
> >
> >  print 'Now x =', w, 'and y = ' , z
> >
> >  return w
> >
> > x = switch(x,y)
> >
> >
> >
> >  How am I supposed to do so I can  return also a value to the variable y
> WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?
> >
> >
> >
> > thanks in advance
>
> Not sure I understand the problem but I think the answer is to put
> multiple values in a list and return the list.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Steven D'Aprano
On Sun, 22 Dec 2013 14:49:43 -0500, Ned Batchelder wrote:

> On 12/22/13 2:10 PM, Frank Cui wrote:
>> sorry, but what if I need to have different parameters in these
>> functions ?
> 
> Frank, welcome to the group.  Common convention is to put your response
> below the exiting message, so that the conversation continues down the
> page.

Ideally responses should be *interleaved* between parts of the quoted 
message, rather than just dumped at the end. The idea is that it's a 
conversation:

Fred said:
-> How do I exfoliate my monkey?

Get a friend to hold it down while you rub it all over 
with Extra Strength Monkey Exfoliating Cream. When you 
are done, give it a banana as a reward.

-> Once I have my exfoliated monkey, how do I convince
-> others that it is my child?

Dress it in children's clothes, and make sure you tell 
people that he or she has a very sensitive artistic 
personality, and that is why you allow it to climb the
walls.


sort of thing. This also gives the writer the opportunity to trim out 
parts of the irrelevant text which is no longer relevant to the 
conversation, although it is considered polite to give some indication, 
usually [snip] or [...], that you have done so.

See Wikipedia's article on posting styles for more information:

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



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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Gregory Ewing

Frank Cui wrote:


Someone else wrote:
 >
 > Frank, welcome to the group. Common convention is to put your response
 > below the exiting message, so that the conversation continues down 
the page.


Thanks for informing the rules.


He forgot to mention the most important rule,
which is:

DON'T quote the entire message you're replying to!

Only quote small pieces of it, like I did above,
just enough to establish context. Then put your
reply to that point under the quoted text.

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Steven D'Aprano
On Sun, 22 Dec 2013 15:37:04 -0300, Frank Cui wrote:

> hey guys,
> I have a requirement where I need to sequentially execute a bunch of
> executions, each execution has a return code. the followed executions
> should only be executed if the return code is 0. is there a cleaner or
> more pythonic way to do this other than the following ? 
> if a() == 0:
> if b() == 0:
> c()

I don't believe there is a clean way to deal with error return codes in 
*any* language, but certainly not Python.

If you only have a few such functions, you can mis-use boolean operators 
to get the result you want, at the cost of misleading code:

a() == 0 and b() == 0 and c()

But that's pretty horrible code, because it looks like you're testing a 
condition when you're really trying to run a, b, c etc. for their side-
effects. Code that relies on side-effects is usually a sign of poor 
design.

A better alternative is to modify the functions so that instead of 
returning 0 on failure and (I'm guessing here) None on success, they 
raise an exception instead. Instead of:

def a():
do_this()
do_that()
if condition:
return 0
do_something_else()


you re-write it as:

def a():
do_this()
do_that()
if condition:
raise SomeError("something broke")
do_something_else()


Then you can do this:


try:
a()
b()
c()
except SomeError:
handle_error()


What if you can't edit all the various a, b, c functions because other 
parts of your code rely on them returning an error result? That's easy, 
you just need an adaptor:

import functools

def adapt(func):
@functools.wraps(func)
def inner(*args, **kwargs):
result = func(*args, **kwargs)
if result == 0:
raise SomeError("some message")
return inner


try:
adapt(a)()
adapt(b)()
adapt(c)()
except SomeError:
handle_error()


Another option really only applies if all the functions use the same set 
of arguments.

def chain(list_of_functions, *args, **kwargs):
for func in list_of_functions:
result = func(*args, **kwargs)
if result == 0:
break


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


Re: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Steven D'Aprano
Unfortunately, the original post seems to have gone missing here, so 
please excuse me for breaking threading.

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:
> basically what I wanna do is this :
> 
> x = 4
> y = 7
> 
> def switch (z,w):
> ***this will switch z to w and vice verca***
> c= z
> z=w
> w=c
> print 'Now x =', w, 'and y = ' , z
> return w
>
> x = switch(x,y)
> 
>
>  How am I supposed to do so I can  return also a value to the variable
>  y WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?


To swap two values in Python (or for that matter, three or thirty-three 
values!) just re-assign the values. Python guarantees that this will work:

x = 23
y = 42
x, y = y, x

x now has the value that y had, and y has the value that x had. There is 
no need for a temporary value, and no need for a "switch" function.

To return more than one value from a function, return a list or a tuple. 
Normally we use a tuple:


def sum_and_product(x, y):
sum = x + y
product = x*y
return (sum, product)


a = 100
b = 2
s, p = sum_and_product(a, b)

Now s will have the value 102 and p will have the value 200.




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


Re: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Dave Angel
On Sun, 22 Dec 2013 15:41:06 -0800 (PST), Bob Rashkin 
 wrote:

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:
>  How am I supposed to do so I can  return also a value to the 
variable y WITHOUT printing 'Now x =', w, 'and y = ' , z   a second 
time ?


You are apparently asking 3 questions. 


To exchange 2 values, use the tuple-unpack approach.

a, b = b, a

To get the equivalent of multiple return values,  return a tuple.

def myfunc (a):
x = a*a
y = 2+a
return x, y

p , q = myfunc (5)

To avoid executing your print twice, call the function only once.

And a bonus one: to avoid my getting a blank message in this text 
newsgroup,  post in text,  not html.


--
DaveA

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


Re: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Steven D'Aprano
Something funny is going on here, not only has the original gone missing,
but my reply apparently has also gone missing. Let me try again, and
apologies for if you see duplicate messages.

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:

> basically what I wanna do is this :
> 
> x = 4
> y = 7
> 
> def switch (z,w):
> ***this will switch z to w and vice verca***
>  c= z
>  z=w
>  w=c
>  print 'Now x =', w, 'and y = ' , z
>  return w
> 
> x = switch(x,y)
> 
>
>  How am I supposed to do so I can  return also a value to the variable y
>  WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?


There is no need for a function to swap two values. In Python, if you want
to swap two values (or three, or thirty-three for that matter!) just
reassign them all at once.

x = 23
y = 42
x, y = y, x


Python guarantees that after this, x will have the value that y had, and y
will have the value that x had. No need for a function!


To return two or more values from a function, use a tuple:


def sum_and_product(a, b):
"""Return the sum and product of a and b."""
sum = a+b
product = a*b
return (sum, product)


s, p = sum_and_product(100, 2)


s will now have the value 102, and p the value 200.


-- 
Steven

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


Re: How can i return more than one value from a function to more than one variable

2013-12-22 Thread Steven D'Aprano
Something funny is going on here, not only has the original gone missing,
but my reply apparently has also gone missing. Let me try again, and
apologies for if you see duplicate messages.

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:

> basically what I wanna do is this :
> 
> x = 4
> y = 7
> 
> def switch (z,w):
> ***this will switch z to w and vice verca***
>  c= z
>  z=w
>  w=c
>  print 'Now x =', w, 'and y = ' , z
>  return w
> 
> x = switch(x,y)
> 
>
>  How am I supposed to do so I can  return also a value to the variable y
>  WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?


There is no need for a function to swap two values. In Python, if you want
to swap two values (or three, or thirty-three for that matter!) just
reassign them all at once.

x = 23
y = 42
x, y = y, x


Python guarantees that after this, x will have the value that y had, and y
will have the value that x had. No need for a function!


To return two or more values from a function, use a tuple:


def sum_and_product(a, b):
"""Return the sum and product of a and b."""
sum = a+b
product = a*b
return (sum, product)


s, p = sum_and_product(100, 2)


s will now have the value 102, and p the value 200.



-- 
Steven

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


testing

2013-12-22 Thread Steven D'Aprano
Is this thing still working?

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


Re: testing

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 11:50 AM, Steven D'Aprano
 wrote:
> Is this thing still working?

Working fine. I saw three messages from you in the other thread.

Sending to you as well as the list in case you're not receiving.

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Roy Smith
In article <52b782db$0$6599$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> Code that relies on side-effects is usually a sign of poor 
> design.

I don't understand what you're trying to say there.  A bit later in your 
post, you wrote:

try:
a()
b()
c()
except SomeError:
handle_error()

Clearly, since the return values of a(), b(), and c() aren't saved, the 
only reason they're getting called is for their side effects.  And I 
don't see anything wrong with that.

BTW, there's a pattern we use a bunch in the Songza server code, which 
is sort of this, but in reverse.  We'll have a bunch of possible ways to 
do something (strategies, to use the pattern vernacular), and want to 
try them all in order until we find one which works.  So, for example:

classes = [ClientDebugPicker,
   StatefulSongPicker,
   SWS_SequentialSongPicker,
   StandardSongPicker]
for cls in classes:
picker = cls.create(radio_session, station, artist)
if picker:
return picker
else:
assert 0, "can't create picker (classes = %s)" % classes

Each SongPicker subclass encapsulates some logic for how to pick the 
next song.  It can also decide if the strategy it implements is 
appropriate for the particular request; create() either returns an 
instance of the class, or None.  Returning None means, "I'm not the 
right picker for this request; try the next one and see what he says".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: testing

2013-12-22 Thread Roy Smith
In article <52b788bb$0$6599$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> Is this thing still working?

Yes.  Do you want to know how many times your previous message was 
posted? :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie question. Are those different objects ?

2013-12-22 Thread alex23

On 21/12/2013 2:00 AM, Mark Lawrence wrote:

Shall I write a PEP asking for a language change which
requires that that stupid = sign is replaced by a keyword reading
something like
thenameonthelefthandsideisassignedtheobjectontherighthandside ?


I propose:

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 12:24 PM, Roy Smith  wrote:
> Each SongPicker subclass encapsulates some logic for how to pick the
> next song.  It can also decide if the strategy it implements is
> appropriate for the particular request; create() either returns an
> instance of the class, or None.  Returning None means, "I'm not the
> right picker for this request; try the next one and see what he says".

But in that instance, the picker has done nothing. The main effect is
to return a value, and since it returned None, you go on to do
something else.

This looks fine:

foo = a() or b() or c()

And it also looks like it would be safe to drop one of the calls if
you know it won't succeed:

if no_way_that_b_will_work:
foo = a() or c()

The point about side effects is that b() still has to be called, here,
and the original statement doesn't make that clear. When you call a
function and ignore its return value, you're clearly doing it for its
side effects. Imagine this:

width_required = max(len(foo),len(bar),len(quux))

Any sane reader is going to assume that the length checks aren't going
to have side effects... but they could! Imagine if testing the length
of something forced it to be loaded into memory, thus triggering any
exception that would otherwise not be triggered until the thing got
loaded much later. Vaguely plausible, but bad design because it's
extremely unclear.

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Steven D'Aprano
Roy Smith wrote:

> In article <52b782db$0$6599$c3e8da3$54964...@news.astraweb.com>,
>  Steven D'Aprano  wrote:
> 
>> Code that relies on side-effects is usually a sign of poor
>> design.
> 
> I don't understand what you're trying to say there.

I'm trying to say that code that relies on side-effects is usually a sign of
poor design. Is that more clear now? :-)

I'm not a functional programming zealot, but imperative programming that
relies on side-effects is often harder to reason about than functional
style, due to lack of locality in its effects. With functions that
communicate only through their input arguments and output result, you don't
have to look far to see the effects the function call has: it is *only* in
the return result. But if it has side-effects, you potentially have to
inspect the entire program and environment to see what it has done.

Now of course sometimes the whole point of the function is to have a
side-effect (print something, delete or save a file, start up the car's
engine, ...) and even functional languages usually have some facility for
side-effects. And we can often limit the harm of relying on side-effects
but narrowly constraining what those side-effects are.

E.g. list.append has a very narrow and well-defined side-effect, which makes
it relatively easy to reason about it. But still not as easy as perhaps we
would like:

alist = blist = [1, 2, 4, 8]
# later on
alist.append(16)  # operates by side-effect
# and still later on
assert blist == [1, 2, 4, 8]  # FAILS!!!


A side-effect free language might make list.append return a new list with
the extra value appended, and then the above would not occur. But I
digress.

The point is, I'm not saying that imperative code that operates via
side-effects is always harmful. There are degrees of badness.


> A bit later in your 
> post, you wrote:
> 
> try:
> a()
> b()
> c()
> except SomeError:
> handle_error()
> 
> Clearly, since the return values of a(), b(), and c() aren't saved, the
> only reason they're getting called is for their side effects.

That's not my design :-)


> And I don't see anything wrong with that.

And quite frankly, neither do I. But I don't know what a, b and c actually
do.


> BTW, there's a pattern we use a bunch in the Songza server code, which
> is sort of this, but in reverse.  We'll have a bunch of possible ways to
> do something (strategies, to use the pattern vernacular), and want to
> try them all in order until we find one which works.

Sounds reasonable. You're not operating by side-effect, since you actually
do want the result generated by the strategy. Presumably the strategy
signature is to return None on failure, or instance on success. (I see
below that's exactly what you do.)


> So, for example: 
> 
> classes = [ClientDebugPicker,
>StatefulSongPicker,
>SWS_SequentialSongPicker,
>StandardSongPicker]
> for cls in classes:
> picker = cls.create(radio_session, station, artist)
> if picker:
> return picker

This seems perfectly reasonable up. The strategy either returns a picker, in
which case you are done, or it returns None and you continue. No
side-effects are involved.


> else:
> assert 0, "can't create picker (classes = %s)" % classes

¡Ay, caramba! I was with you until the very last line. The above code is
possibly buggy and inappropriately designed. (I may be completely
misinterpreting this, in which case feel free to ignore the following
rant.)

First, the bug: there are circumstances where no exception is raised even if
all the strategies fail. (If the StandardSongPicker is guaranteed to
succeed, then obviously my analysis is wrong.) In this case, then any code
following the for-else will execute. Since this is in a function, and there
doesn't seem to be any following code, that means that your function will
return None instead of a valid picker. Does the rest of your code check for
None before using the picker? If not, you have a bug waiting to bite.

Second, the poor design. When it works as expected, failure is indicated by
AssertionError. Why AssertionError? Why not ImportError, or
UnicodeEncodeError, or ZeroDivisionError, or any other of the dozens of
inappropriate errors that the code could (but shouldn't) raise? I guess
nobody here would write code that looks like this by design:

try:
picker = select_picker(radio_session, station, artist)
except EOFError:
handle_no_picker_case()


just because "raise EOFError" required less typing than raising some more
appropriate exception. So why would we write:

try:
picker = select_picker(radio_session, station, artist)
except AssertionError:
handle_no_picker_case()


just because "assert" required less typing than raising some more
appropriate exception? assert is not a short-cut for "raise
SomeGenericException". AssertionError has a specific meaning, and it is
sloppy to misus

python socket query

2013-12-22 Thread smilesonisamal
Hi,
   I am trying to write a TCP socket program in python. I am using python 2.6 
in linux. 

I referred following link:
http://www.ibm.com/developerworks/linux/tutorials/l-pysocks/section4.html
I am actually writing the client-side stream socket.
I wrote a small program which creates the socket, bind to the socket, connect 
to socket and send() close(). I see that there is no reply coming from server 
and the TCP disconnect happens.
import socket

def tcp(host, request, port=34567):

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

s.send(request)

reply = s.recv(2**14)

s.close()

return reply

My problem is even if the request is sent the length(reply) is is 0. I tried to 
put a timeout of 1 sec s.settimeout() call after the send call but it doesnot 
help.

I tried by commenting s.close() still it did not work.

Any idea what is the problem?

Regards

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 1:33 PM, Steven D'Aprano
 wrote:
> Anyway, I may be completely misinterpreting what I'm reading. Perhaps the
> assertion is checking a function invariant ("one of the strategies will
> always succeed") in which case you're doing it exactly right and I should
> shut up now :-)

Or maybe it has a lengthy piece of error trapping code that wasn't
germane to the discussion, and for brevity was squished down to a
quick little assert :)

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


Re: python socket query

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 2:05 PM,   wrote:
> I wrote a small program which creates the socket, bind to the socket, connect 
> to socket and send() close(). I see that there is no reply coming from server 
> and the TCP disconnect happens.
> import socket
>
> def tcp(host, request, port=34567):
>
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> s.connect((host, port))
>
> s.send(request)
>
> reply = s.recv(2**14)
>
> s.close()
>
> return reply

First off, your formatting has become mangled. This is likely to be
because of Google Groups, which tends to make a mess of posts. I
strongly recommend you get a better newsreader, such as Thunderbird,
or switch to the mailing list:

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

I'm going to assume that (a) the code you've provided is all part of
the tcp() function, and (b) that you are actually calling tcp()
somewhere and seeing what comes back. But once you sort out your
posting issues, you may want to post a complete program (probably not
more than a couple of additional lines beyond what you have above) so
we know what's actually going on.

Terminology point: You mention binding to the socket. In networking,
"bind" has a specific meaning - binding to an address, usually done
for servers, and something you're not doing here.

Are you sure the server's doing something? I tried what you had there
(albeit under Python 3.3), and it seems to be fine. Perhaps you need
to terminate the request with something - maybe a newline. The send()
method will send exactly the bytes you give it, nothing more.

Can you telnet to the server?

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


Airplane mode control using Python?

2013-12-22 Thread Kevin Peterson
Hi, 

I am trying to control Aeroplane mode on Android using Python code. I am 
running QPyPlus python. When I execute this code(that is widespread in the 
net), 

#!/usr/bin/python 
import android droid = android.Android()
# go to airplane mode
 droid.toggleAirplaneMode()
 
droid.makeToast('exiting')

I get the error 'no such attribute Android()'. 

One important thing is, I want to be able to do this without the need to reboot 
the Android device and any other working solution is also fine long as it is 
invokeable through Python.

Thanks,
Kevin Peterson


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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 2:10 PM, Dennis Lee Bieber
 wrote:
> Having spent 22 years with VMS, 0 -> success is still a problem to me.
> Odd result codes (aka True) were 1-success/3-information, even results
> (False) were 0-warning/2-error/4-fatal

Having spent a similar amount of time with Unix, C, and various APIs,
I'm quite used to 0 meaning success and nonzero meaning error.

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


Re: Airplane mode control using Python?

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 2:20 PM, Kevin Peterson  wrote:
> I am trying to control Aeroplane mode on Android using Python code. I am 
> running QPyPlus python. When I execute this code(that is widespread in the 
> net),
>
> #!/usr/bin/python
> import android droid = android.Android()
> # go to airplane mode
>  droid.toggleAirplaneMode()
>
> droid.makeToast('exiting')
>
> I get the error 'no such attribute Android()'.

Python code is sensitive to changes in whitespace. The above is
actually a syntax error, because lines have been merged and indented
incorrectly. You seem to be posting from Google Groups, which may be
why it's messed up; I recommend switching to something else, like
Mozilla Thunderbird, or subscribing instead to the mailing list (with
all the same content):

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

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


Re: Airplane mode control using Python?

2013-12-22 Thread Michael Torrie
On 12/22/2013 08:20 PM, Kevin Peterson wrote:
> Hi, 
> 
> I am trying to control Aeroplane mode on Android using Python code.
> I am running QPyPlus python. When I execute this code(that is widespread
> in the net),
> 
> #!/usr/bin/python 
> import android droid = android.Android()
> # go to airplane mode
>  droid.toggleAirplaneMode()
>  
> droid.makeToast('exiting')
> 
> I get the error 'no such attribute Android()'. 

Is that really how your code is formatted? The import line is an error.

try:

import android


droid = android.Android()

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Mark Lawrence

On 23/12/2013 03:22, Chris Angelico wrote:

On Mon, Dec 23, 2013 at 2:10 PM, Dennis Lee Bieber
 wrote:

 Having spent 22 years with VMS, 0 -> success is still a problem to me.
Odd result codes (aka True) were 1-success/3-information, even results
(False) were 0-warning/2-error/4-fatal


Having spent a similar amount of time with Unix, C, and various APIs,
I'm quite used to 0 meaning success and nonzero meaning error.

ChrisA



Another C thing to complain about, with functions like malloc the status 
code and value returned are one and the same thing, except that NULL is 
failure in this case.


--
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: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 2:43 PM, Mark Lawrence  wrote:
> Another C thing to complain about, with functions like malloc the status
> code and value returned are one and the same thing, except that NULL is
> failure in this case.

How's that a problem? Python has the same:

memory.get(1234)

will return a bit of memory, or None if it can't get any. Not
materially different. Remember, C doesn't have exceptions. In C++, the
'new' operator will throw an exception if it can't provide memory.

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Mark Lawrence

On 23/12/2013 03:45, Chris Angelico wrote:

On Mon, Dec 23, 2013 at 2:43 PM, Mark Lawrence  wrote:

Another C thing to complain about, with functions like malloc the status
code and value returned are one and the same thing, except that NULL is
failure in this case.


How's that a problem? Python has the same:


Remembering to check it?



memory.get(1234)


You learn something new every day or April 1st come early?



will return a bit of memory, or None if it can't get any. Not
materially different. Remember, C doesn't have exceptions. In C++, the
'new' operator will throw an exception if it can't provide memory.

ChrisA




--
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: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 2:54 PM, Mark Lawrence  wrote:
>> memory.get(1234)
>
>
> You learn something new every day or April 1st come early?

memory = {1:"Foo", 12:"Bar", 123:"Quux"}

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


Re: Airplane mode control using Python?

2013-12-22 Thread Ned Batchelder

On 12/22/13 10:41 PM, Michael Torrie wrote:

On 12/22/2013 08:20 PM, Kevin Peterson wrote:

Hi,

I am trying to control Aeroplane mode on Android using Python code.
I am running QPyPlus python. When I execute this code(that is widespread
in the net),

 #!/usr/bin/python
 import android droid = android.Android()
 # go to airplane mode
  droid.toggleAirplaneMode()

 droid.makeToast('exiting')

I get the error 'no such attribute Android()'.


Is that really how your code is formatted? The import line is an error.

try:

import android


droid = android.Android()



The OP reported an error of "no such attribute Android", it's pretty 
obvious that he isn't getting a syntax error.  We can assume the code 
has been mangled in the posting.


Your code sample (once the obvious formatting errors have been fixed) is 
identical to ones I've found online, so I assume it should work.


My best guess is that you have named your own file android.py, shadowing 
the library you're trying to import.  Name it something else, delete all 
the *.pyc files in your directory, and try again.


--
Ned Batchelder, http://nedbatchelder.com

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


Re: cascading python executions only if return code is 0

2013-12-22 Thread Roy Smith
In article <52b7a0e4$0$29994$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> Anyway, I may be completely misinterpreting what I'm reading. Perhaps the
> assertion is checking a function invariant ("one of the strategies will
> always succeed") in which case you're doing it exactly right and I should
> shut up now :-)

Yes :-)

More specifically, the assertion exception will get caught way up in 
some django middleware which will log a stack trace and return a HTTP 
50-something.  This will typically be followed by somebody like me 
noticing the stack dump and trying to figure out WTF happened.

Assertions are great tools.  People should use them more often.  In a 
sense, they're executable comments.  They're a programmer's way of 
standing on a hilltop and shouting to all the world, "I swear to you, 
this is true.  There may be a gazillion lines of code out there and 
GBytes of program state, but right here, right now, within this circle 
I've drawn in the sand, I know this to be true, and you can depend on 
that.  You can make it part of the foundation on which you begin to 
reason about program behavior.  Furthermore, if it turns out not to be 
true, you don't have to worry about figuring out who's fault it is.  I 
hereby declare that it's my fault".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 3:57 PM, Roy Smith  wrote:
> More specifically, the assertion exception will get caught way up in
> some django middleware which will log a stack trace and return a HTTP
> 50-something.  This will typically be followed by somebody like me
> noticing the stack dump and trying to figure out WTF happened.
>
> Assertions are great tools.  People should use them more often.

You do have to be careful though, because they can be compiled out. If
it really is a "can't happen", then sure, but encouraging people to
use them for potentially obscure cases may be dangerous - if you never
happen to hit on it during development and then run with assertions
disabled, you won't see that stack trace.

However, they're still a lot more executable than other forms of comment :)

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


Re: Airplane mode control using Python?

2013-12-22 Thread rurpy
On 12/22/2013 08:33 PM, Chris Angelico wrote:
> On Mon, Dec 23, 2013 at 2:20 PM, Kevin Peterson  wrote:
>> I am trying to control Aeroplane mode on Android using Python code.
>> I am running QPyPlus python. When I execute this code(that is
>> widespread in the net),
>> 
>>#!/usr/bin/python
>>import android droid = android.Android()
>># go to airplane mode
>> droid.toggleAirplaneMode()
>>
>>droid.makeToast('exiting')
>> 
>> I get the error 'no such attribute Android()'.
> 
> Python code is sensitive to changes in whitespace. The above is 
> actually a syntax error, because lines have been merged and indented 
> incorrectly. You seem to be posting from Google Groups, which may be 
> why it's messed up; I recommend switching to something else, like 
> Mozilla Thunderbird, or subscribing instead to the mailing list
> (with all the same content)

My electricity went out right around the time the OP posted 
from Google Groups, that too was undoubtedly GG's fault.

Come on Chris, it is just as easy to make typo or copy-and-
paste errors in any other software as GG, there is no evidence
that it was GG's fault.

If you want to recommend the mailing list, fine, but please 
don't make stupid, unfounded, accusatory suggestions.

Kevin: just for your own info, there are a few people here
who despise Google Groups.  I and many other people post
from Google Groups regularly and it works fine.  You might
want to take a look at 
 https://wiki.python.org/moin/GoogleGroupsPython
for some ways to reduce the annoyance factor for the anti-GG 
clique here.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 2nd Try: Trouble writing lines to file that include line feeds - Newbie

2013-12-22 Thread Dan Healy
Solved. Simply change the 'w' from the file.open method to an 'a' for append

On Sunday, December 22, 2013 7:55:28 PM UTC-5, Dan Healy wrote:
> Overview: I'm attempting to read strings from a serial port. Each string ends 
> with a carriage return and line feed. I want to write those strings to a 
> file, like a log file. So, if I send P1 and the P2 on a new line, I would 
> expect to open this file and find (line 1) P1 (line 2) P2. 
> 
> 
> 
> Problem: The file only contains P2. It always overwrites the first line. I 
> can send 20 strings and the file will always contain the last string 
> received. 
> 
> 
> 
> Code: 
> 
> 
> 
> #Import the serial module 
> 
> import serial 
> 
> 
> 
> #Open the serial port w/ settings 
> 
> ser=serial.Serial( 
> 
> port="/dev/ttyUSB0", 
> 
> baudrate=9600, 
> 
> timeout=None) 
> 
> 
> 
> #Print data received on the serial port after removing the CR and LF 
> characters 
> 
> while True: 
> 
> rawcode=ser.readline() 
> 
> codelog=open('/home/pi/avdms/codes.log','w') 
> 
> codelog.write(rawcode) 
> 
> codelog.close()

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


Re: Airplane mode control using Python?

2013-12-22 Thread Chris Angelico
On Mon, Dec 23, 2013 at 3:52 PM,   wrote:
> Come on Chris, it is just as easy to make typo or copy-and-
> paste errors in any other software as GG, there is no evidence
> that it was GG's fault.

Actually, formatting errors ARE often caused by Google Groups. Maybe
it wasn't in this instance, but I have seen several cases of GG
mangling code formatting, so this was a perfectly reasonable theory.

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


Re: Airplane mode control using Python?

2013-12-22 Thread Kevin Peterson
I will take care.

Thanks,


On Mon, Dec 23, 2013 at 10:22 AM,  wrote:

> On 12/22/2013 08:33 PM, Chris Angelico wrote:
> > On Mon, Dec 23, 2013 at 2:20 PM, Kevin Peterson 
> wrote:
> >> I am trying to control Aeroplane mode on Android using Python code.
> >> I am running QPyPlus python. When I execute this code(that is
> >> widespread in the net),
> >>
> >>#!/usr/bin/python
> >>import android droid = android.Android()
> >># go to airplane mode
> >> droid.toggleAirplaneMode()
> >>
> >>droid.makeToast('exiting')
> >>
> >> I get the error 'no such attribute Android()'.
> >
> > Python code is sensitive to changes in whitespace. The above is
> > actually a syntax error, because lines have been merged and indented
> > incorrectly. You seem to be posting from Google Groups, which may be
> > why it's messed up; I recommend switching to something else, like
> > Mozilla Thunderbird, or subscribing instead to the mailing list
> > (with all the same content)
>
> My electricity went out right around the time the OP posted
> from Google Groups, that too was undoubtedly GG's fault.
>
> Come on Chris, it is just as easy to make typo or copy-and-
> paste errors in any other software as GG, there is no evidence
> that it was GG's fault.
>
> If you want to recommend the mailing list, fine, but please
> don't make stupid, unfounded, accusatory suggestions.
>
> Kevin: just for your own info, there are a few people here
> who despise Google Groups.  I and many other people post
> from Google Groups regularly and it works fine.  You might
> want to take a look at
>  https://wiki.python.org/moin/GoogleGroupsPython
> for some ways to reduce the annoyance factor for the anti-GG
> clique here.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Numpy Folder Structure

2013-12-22 Thread Chandru Rajendran
Hi all,

Please help me with how we can make our folder structure similar to Numpy 
Folder structure , so that we can make our installer similar to the numpy. With 
the folder structure now I am having , if I install , it is directly installing 
without the folder in site packages unlike numpy.

Thanks & regards,
Chandru

 CAUTION - Disclaimer *
This e-mail contains PRIVILEGED AND CONFIDENTIAL INFORMATION intended solely
for the use of the addressee(s). If you are not the intended recipient, please
notify the sender by e-mail and delete the original message. Further, you are 
not
to copy, disclose, or distribute this e-mail or its contents to any other 
person and
any such actions are unlawful. This e-mail may contain viruses. Infosys has 
taken
every reasonable precaution to minimize this risk, but is not liable for any 
damage
you may sustain as a result of any virus in this e-mail. You should carry out 
your
own virus checks before opening the e-mail or attachment. Infosys reserves the
right to monitor and review the content of all messages sent to or from this 
e-mail
address. Messages sent to or from this e-mail address may be stored on the
Infosys e-mail system.
***INFOSYS End of Disclaimer INFOSYS***
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Airplane mode control using Python?

2013-12-22 Thread Mark Lawrence

On 23/12/2013 04:52, ru...@yahoo.com wrote:

On 12/22/2013 08:33 PM, Chris Angelico wrote:

On Mon, Dec 23, 2013 at 2:20 PM, Kevin Peterson  wrote:

I am trying to control Aeroplane mode on Android using Python code.
I am running QPyPlus python. When I execute this code(that is
widespread in the net),

#!/usr/bin/python
import android droid = android.Android()
# go to airplane mode
 droid.toggleAirplaneMode()

droid.makeToast('exiting')

I get the error 'no such attribute Android()'.


Python code is sensitive to changes in whitespace. The above is
actually a syntax error, because lines have been merged and indented
incorrectly. You seem to be posting from Google Groups, which may be
why it's messed up; I recommend switching to something else, like
Mozilla Thunderbird, or subscribing instead to the mailing list
(with all the same content)


My electricity went out right around the time the OP posted
from Google Groups, that too was undoubtedly GG's fault.

Come on Chris, it is just as easy to make typo or copy-and-
paste errors in any other software as GG, there is no evidence
that it was GG's fault.

If you want to recommend the mailing list, fine, but please
don't make stupid, unfounded, accusatory suggestions.

Kevin: just for your own info, there are a few people here
who despise Google Groups.  I and many other people post
from Google Groups regularly and it works fine.  You might
want to take a look at
  https://wiki.python.org/moin/GoogleGroupsPython
for some ways to reduce the annoyance factor for the anti-GG
clique here.



We are *NOT* anti-GG, we've anti-reading double spaced crap, continuous 
single lines instead of proper paragraphs and badly formed Python source 
code amongst other things.  We *DON'T* as a rule of thumb get this 
problem from any source except GG.


--
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


Daemonify my python script on Android

2013-12-22 Thread Kevin Peterson
Hi,

I want to daemonify my python script on Android device. That is, it should
be automatically invoked on boot up.

Appreciate your help.

Thanks

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