Re: [Tutor] decorators (the "at" sign)?

2010-10-26 Thread Lie Ryan
On 10/26/10 13:46, Alex Hall wrote:
> Hi all,
> Now that I am able to run the source code of an open source
> application I hope to one day help develop, I am trying to understand
> how it works. One thing I keep seeing is an at sign followed by a
> word, usually (maybe always) immediately preceeding a function
> definition. For example, and I know this exact code will not make much
> sense, but it gives the idea:
> class Bing(Messages, Updating, Dismissable):
> 
>  @set_index
>  def get_url(self, index=None):
>   return self.storage[index]['Url']
> 
> What is the "@set_index" for? Specifically, what is the at sign doing?
> Google was only able to provide me with a very vague idea of what is
> going on, though it seems to crop up a lot in classmethod and
> staticmethod calls (not sure about those either). I read PEP 318, but
> it was not much help since I am coming at this having no idea what I
> am looking at. The PEP did explain why I have never run into this
> before, though - it is apparently specific to Python. I see this sort
> of thing all over this source code so it seems like a good idea to get
> exactly what it is for. TIA!


The decorator syntax is really just a shorthand, from this:

@decorator
def func(arg):
pass

is equivalent to:

def func(arg):
pass
func = decorator(func)


basically, a decorator is a function that takes an function as a
parameter/callable and (usually) returns another function/callable as
return value.


A slightly advanced usage of decorator:

def trace(func):
""" trace will print the func's name, the number of times
func have been called, the arguments it's called with,
and the return value of func whenever func is called.
"""

# define an inner function
def _decorator(arg):
print ("The %sth call of %s with arg: %s" %
(_decorator._numcall, func.__name__, arg))

_decorator._numcall += 1
ret = func(arg)

print "finished", func.__name__, "returns:", ret

return ret

# this is used to store the number of times
# the decorated function is called
_decorator._numcall = 0

# disable the decorator when debugging is enabled
if __debug__: # or: return _decorator if __debug__ else func
return _decorator
else:
return func

@trace
def twice(arg):
return 2 * arg
# the @trace makes it as if you do this:
# twice = trace(twice)



$ # let's start the program
$ python decor.py
The 0th call of twice() with arg: 30
finished twice() returns: 60
The 1th call of twice() with arg: 3
finished twice() returns: 6
The 2th call of twice() with arg: 4
finished twice() returns: 8
74
$
$ # now call it with debugging disabled:
$ python -O decor.py
74


another nifty use of decorator is for event handling for a hypothetical
GUI toolkit (I've yet to actually see a toolkit that uses this syntax yet):

@button.on_click
def shoot(button):
...
@window.on_keypress('p')
def pause(key):
...


other built-in functions designed for decorator syntax is @property,
@classmethod, and @instancemethod. Decorator can become extremely
powerful when combined with the descriptor protocol (.__get__, .__set__).

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess Popen PIPE error

2010-10-26 Thread Sean Carolan
What am I doing wrong here?

>>> from subprocess import Popen, PIPE
>>> cmd = 'ls -l'
>>> p = Popen(cmd, stdout=PIPE, stderr=PIPE)
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
  File "/usr/lib64/python2.4/subprocess.py", line 993, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess Popen PIPE error

2010-10-26 Thread Abhijeet Rastogi
Please read the documentation of Popen. You cannot pass arguments like that.

>>> from subprocess import Popen,PIPE
>>> import shlex
>>> cmd="ls -l"
>>> cmd=shlex.split(cmd)
>>> p = Popen(cmd,stdout=PIPE,stderr=PIPE)

or simply that means

>>> p = Popen(['ls','-l'],stdout=PIPE,stderr=PIPE)

Hope I have made my point clear. The problem occuring is that there is no
binary that has name as "ls -l". Python cannot understand that "-l" is an
argument until you pass it this way.


On Tue, Oct 26, 2010 at 6:52 PM, Sean Carolan  wrote:

> What am I doing wrong here?
>
> >>> from subprocess import Popen, PIPE
> >>> cmd = 'ls -l'
> >>> p = Popen(cmd, stdout=PIPE, stderr=PIPE)
> Traceback (most recent call last):
>  File "", line 1, in ?
>  File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
>errread, errwrite)
>  File "/usr/lib64/python2.4/subprocess.py", line 993, in _execute_child
>raise child_exception
> OSError: [Errno 2] No such file or directory
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Abhijeet Rastogi (shadyabhi)
http://www.google.com/profiles/abhijeet.1989
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess Popen PIPE error

2010-10-26 Thread Abhijeet Rastogi
Ya. Do it using python. Why do you want to use bash when you already have
python?

See, do something like this:-

import os
alldirs = os.listdir("/path/to/dir")

DIRS = [] #Only the dirs you are interested in

for i in alldirs:
  if i.find("deploy") is -1: L.append(i)
  if i.find("TEMPLATE") is -1: L.append(i)

#Now L contains all the required dirs.

Hope it helps.

On Tue, Oct 26, 2010 at 9:19 PM, Sean Carolan  wrote:

> > Here is the bash one-liner that generates my list,
> > with one name per line:
> >
> > ls -d */ | grep -v -E 'deploy|TEMPLATE' | sed 's/\///'
> >
> > How would you get the output of this into a python list that could
> > then be used in the script?  Please forgive my ignorance; I've read
> > through the documentation but am still not clear on this aspect.
>
> Would this be easier to accomplish using os.listdir()?.  Basically I
> want to make a list of directories, excluding files and the
> directories or files containing "deploy" and "TEMPLATE".
>



-- 
Abhijeet Rastogi (shadyabhi)
http://www.google.com/profiles/abhijeet.1989
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-26 Thread Roy Hinkelman
I am posting here as well as a PHP list since I am now getting an odd python
error.



Rance: Thanks for the note. I get the same error with system or exec or
passthru



Now, this is very strange.



I made the command line string more explicit, and now it recognizes the .py
script but returns a python error:



Content:

Data: ImportError: No module named mechanize

Command: C:\WINDOWS\system32\cmd.exe C:\Program%20Files\Python26\python.exe
/c D:\Inetpub\AtoZ\hometown\include\weatherFeed.py -c Tampa -s FL



My python script will run correctly in IDE shell and from command line. I
used easy_install to install mechanize. It seems to be recognizing my other
modules (BeautifulSoup, re, urllib2, sys).



So, it seems that the script is being activated by the exec command since I
am now getting a python error. But, why would I get a python error when it
will run from command line?



Here is my PHP:

[code]

  OPTION 1Python Weather Feed for ' . $city . ', ' .
$state . '';



ob_start();

$command = "C:\WINDOWS\system32\cmd.exe
C:\Program%20Files\Python26\python.exe
/c  D:\Inetpub\AtoZ\hometown\include\weatherFeed.py -c " .  $city . " -s " .
$state;



$data = exec($command . " 2>&1", $result);

$content=ob_get_contents();

ob_end_clean();



echo 'Content: ' . $content . '';

echo 'Result: ' . $result . '';

echo 'Data: ' . $data . '';

echo 'Command: ' . $command . '';

include('include\weatherFeed_TEMP.txt')

  ?>

[/code]



and I've modified my python, making it a function [code] #!C:\Program
Files\Python26\python.exe -u # Current weather feed # # Weather page
sources: http://www.weather.gov/ # Capture relevant data, strip unusable
stuff out, fix URLs, display in our HTML page



# import program modules

from BeautifulSoup import BeautifulSoup as B_S import re, urllib2, sys,
mechanize # 'standard' set



### Return small weather table

def weatherSmall(c,s):

cityState = c + ', ' + s

query = 'Chicago, IL' #Test!!!

_URL = "http://www.weather.gov/";



br=mechanize.Browser()

br.open( _URL )

br.select_form( nr=1 ) #assuming form is 2nd form on page

br['inputstring'] = query

html = br.submit()



_soup = B_S(html)



# finding the correct table

_step1 = _soup.findAll('table', limit=7)[6]

col = _step1.findAll('td')

# sys.argv is included below as a test.

_thumb = 'Forecast for ' + query + '' +
str(sys.argv) + '' + str(col[0]) + str(col[1]) +
''

_thumb = _thumb.replace( '11%','50%' )

_thumb = _thumb.replace( '/images/', 'images/weather/' )



#write to txt file TEST

_temp = 'D:\\Inetpub\\AtoZ\\hometown\\include\\weatherFeed_TEMP.txt'

temp = open( _temp, 'w' )

temp.write( _thumb )

temp.close()



return _thumb



city = 'Establish'

state = 'Variables'

count = 0

for ea in sys.argv:

if ea == '-c':

city = sys.argv[count+1]

elif ea == '-s':

state = sys.argv[count+1]

count+=1

_result = str(weatherSmall(city,state))

#print _result

[/code]



Roy Hinkelman

Technical Services

Website Development & Management

707-774-7411

r...@worldtradepress.com





-Original Message-

From: Rance Hall [mailto:ran...@gmail.com]

Sent: Saturday, October 23, 2010 10:25 AM

To: r...@worldtradepress.com

Subject: Re: [Tutor] Problem Passing VARs to Python from PHP & capturing
return string



On Fri, Oct 22, 2010 at 1:28 PM, Roy Hinkelman <
rhinkel...@worldtradepress.com> wrote:

> My script doesn't want to recognize the variables from the exec()

> command in PHP. Plus, it won't capture the results of the script.

>

> This Python script works in IDLE, and I've got some testing code in there.

>

> One Known Unsolved Issue:

> I put Python in C:\Program Files\Python26\python.exe and have tried

> $command = "C:\Program Files\Python26\python.exe

> include/weatherFeed.py -c $city -s $state"; to no avail.

>

> I added .py to Windows IIS Web Service Extensions and to the

> Application Configuration.

>

> Any help appreciated.

>







Ok, so you wrote a Python script to create a text file, and you want PHP to
include that text file in a web page.



I'm assuming that your Python is working on its own.



I also see you are running this from a windows server.



According to the PHP site the exec function takes option arguments that you
are not using:



string exec ( string $command [, array &$output [, int &$return_var ]] )



Might I suggest that you switch from exec to system()



documented here:  http://www.php.net/manual/en/function.system.php



string system ( string $command [, int &$return_var ] )



Since it doesn't appear that your Python script has any output except for
the text file, it might be better to call it from system() because

system() does not care about the output of the called program.



May I also s

Re: [Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-26 Thread Emile van Sebille

On 10/26/2010 12:55 PM Roy Hinkelman said...

I am posting here as well as a PHP list since I am now getting an odd python
error.


The traceback of the python error would help us diagnose the problem but 
it's not been included.  Can you paste in the actual traceback?


Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Summing up numbers in a file

2010-10-26 Thread masawudu bature
How do I sum all occurrences of  a number in a file?
I have a file with a bunch of numbers, each on it's own line:

5
3
11
3
7
3
5
5
11
7
7
...
How do i sum them up so that the output will be ,
5 :  15
3 :   9
11:  22
7 :   21


  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Summing up numbers in a file

2010-10-26 Thread Adam Bark

On 26/10/10 21:20, masawudu bature wrote:

How do I sum all occurrences of  a number in a file?
I have a file with a bunch of numbers, each on it's own line:
5
3
11
3
7
3
5
5
11
7
7
...
How do i sum them up so that the output will be ,
5 :  15
3 :   9
11:  22
7 :   21

Assuming you know how to iterate through a file, you could try saving 
the number of occurrences of each number in the file into a dictionary.

Something like:

if num in my_dict:
my_dict[num] += 1
else:
my_dict[num] = 1

HTH.
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Summing up numbers in a file

2010-10-26 Thread Robert Berman
This certainly looks like a classroom  assignment. Please make an attempt to
solve the problem on your own. If the program fails, please copy the code you
have written and the error messages from the traceback  and someone here will
be more than happy to help you work your way through the problem.

 

Good luck,

 

Robert

 

From: tutor-bounces+bermanrl=cfl.rr@python.org
[mailto:tutor-bounces+bermanrl=cfl.rr@python.org] On Behalf Of masawudu
bature
Sent: Tuesday, October 26, 2010 4:20 PM
To: tutor@python.org
Subject: [Tutor] Summing up numbers in a file

 

How do I sum all occurrences of  a number in a file?

I have a file with a bunch of numbers, each on it's own line:

 

5
3

11
3
7
3
5
5
11
7

7

...

How do i sum them up so that the output will be ,

5 :  15

3 :   9

11:  22

7 :   21

 


  _  

I am using the Free version of SPAMfighter  .
SPAMfighter has removed 16 of my spam emails to date.

Do you have a slow PC? 
Try free scan! 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Summing up numbers in a file

2010-10-26 Thread Emile van Sebille

On 10/26/2010 1:20 PM masawudu bature said...

How do I sum all occurrences of  a number in a file?
I have a file with a bunch of numbers, each on it's own line:

5
3
11
3
7
3
5
5
11
7
7
...
How do i sum them up so that the output will be ,
5 :  15
3 :   9
11:  22
7 :   21




Well, you'll need to read the lines of the file in and group them 
together. Then, for each group, print both the number and the result 
when multiplied by the count.


To do this, you'll need the name of the file and use open to read it in. 
 I'd suggest using a dict to accumulate the groups, and a loop to print 
the results.


What have you got so far?

Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing VARs to Python from PHP & capturing return string

2010-10-26 Thread Roy Hinkelman
I got it working.

As several people mentioned, it was a permissions issue. When I tried the
command line, I had admin access, but from the web page, I had only 'Users'.
I had to manually change permissions for both the Python module 'mechanize'
as well as the txt file the script was writing to.

Now, exec() and passthru() are both working, as in, passing the argument to
python and executing the script. Output Buffer (ob), however, is not. I
still need to write to a temp file.

Thanks for everyone's help.

Roy
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-26 Thread Roy Hinkelman
I am posting here as well as a PHP list since I am now getting an odd python
error.

Rance: Thanks for the note. I get the same error with system or exec or
passthru

Now, this is very strange.

I made the command line string more explicit, and now it recognizes the .py
script but returns a python error:

Content:
Data: ImportError: No module named mechanize
Command: C:\WINDOWS\system32\cmd.exe C:\Program%20Files\Python26\python.exe
/c D:\Inetpub\AtoZ\hometown\include\weatherFeed.py -c Tampa -s FL

My python script will run correctly in IDE shell and from command line. I
used easy_install to install mechanize. It seems to be recognizing my other
modules (BeautifulSoup, re, urllib2, sys).

So, it seems that the script is being activated by the exec command since I
am now getting a python error. But, why would I get a python error when it
will run from command line?

Here is my PHP:
[code]
OPTION 1Python Weather Feed for ' . $city . ',
' . $state . '';

ob_start();
$command = "C:\WINDOWS\system32\cmd.exe
C:\Program%20Files\Python26\python.exe /c
D:\Inetpub\AtoZ\hometown\include\weatherFeed.py -c " .  $city . " -s " .
$state;

$data = exec($command . " 2>&1", $result);
$content=ob_get_contents();
ob_end_clean();

echo 'Content: ' . $content . '';
echo 'Result: ' . $result . '';
echo 'Data: ' . $data . '';
echo 'Command: ' . $command . '';
include('include\weatherFeed_TEMP.txt')
?>
[/code]

and I've modified my python, making it a function
[code]
#!C:\Program Files\Python26\python.exe -u
# Current weather feed
# # Weather page sources: http://www.weather.gov/
# Capture relevant data, strip unusable stuff out, fix URLs, display in our
HTML page

# import program modules
from BeautifulSoup import BeautifulSoup as B_S
import re, urllib2, sys, mechanize # 'standard' set

### Return small weather table
def weatherSmall(c,s):
cityState = c + ', ' + s
query = 'Chicago, IL' #Test!!!
_URL = "http://www.weather.gov/";

br=mechanize.Browser()
br.open( _URL )
br.select_form( nr=1 ) #assuming form is 2nd form on page
br['inputstring'] = query
html = br.submit()

_soup = B_S(html)

# finding the correct table
_step1 = _soup.findAll('table', limit=7)[6]
col = _step1.findAll('td')
# sys.argv is included below as a test. 
_thumb = 'Forecast for ' + query + '' +
str(sys.argv) + '' + str(col[0]) + str(col[1]) +
''
_thumb = _thumb.replace( '11%','50%' )
_thumb = _thumb.replace( '/images/', 'images/weather/' )

#write to txt file TEST
_temp = 'D:\\Inetpub\\AtoZ\\hometown\\include\\weatherFeed_TEMP.txt'
temp = open( _temp, 'w' )
temp.write( _thumb )
temp.close()

return _thumb

city = 'Establish'
state = 'Variables'
count = 0
for ea in sys.argv:
if ea == '-c':
city = sys.argv[count+1]
elif ea == '-s':
state = sys.argv[count+1]
count+=1
_result = str(weatherSmall(city,state))
#print _result
[/code]

Roy Hinkelman
Technical Services
Website Development & Management
707-774-7411
r...@worldtradepress.com

www.WorldTradePress.com (main website)
www.StockMapAgency.com (3700+ Antique & Modern Maps)
www.BestCountryReports.com (country reports for 175 countries)
www.GiantMapArt.com (giant wall maps)
www.WorldTradeRef.com (trade and logistics)
www.GlobalRoadWarrior.com (175-country database) 
www.AtoZMapsOnline.com (worlds largest map database)
www.AtoZtheUSA.com (extensive state facts database)

-Original Message-
From: Rance Hall [mailto:ran...@gmail.com] 
Sent: Saturday, October 23, 2010 10:25 AM
To: r...@worldtradepress.com
Subject: Re: [Tutor] Problem Passing VARs to Python from PHP & capturing
return string

On Fri, Oct 22, 2010 at 1:28 PM, Roy Hinkelman
 wrote:
> My script doesn't want to recognize the variables from the exec() command
in
> PHP. Plus, it won't capture the results of the script.
>
> This Python script works in IDLE, and I've got some testing code in there.
>
> One Known Unsolved Issue:
> I put Python in C:\Program Files\Python26\python.exe and have tried
> $command = "C:\Program Files\Python26\python.exe include/weatherFeed.py -c
> $city -s $state";
> to no avail.
>
> I added .py to Windows IIS Web Service Extensions and to the Application
> Configuration.
>
> Any help appreciated.
>



Ok, so you wrote a Python script to create a text file, and you want
PHP to include that text file in a web page.

I'm assuming that your Python is working on its own.

I also see you are running this from a windows server.

According to the PHP site the exec function takes option arguments
that you are not using:

string exec ( string $command [, array &$output [, int &$return_var ]] )

Might I suggest that you switch from exec to system()

documented here:  http://w

Re: [Tutor] problems with numdifftools

2010-10-26 Thread Bolli

Hey, 

First of all thanks for your response. I am also new to this forum so I
expected to receive an email if somebody replies to my question. Therefore I
just read it today
 
> I am not sure if you are the right persons to contact but if not I
> would appreciate a short notice and maybe an address where I can find
> help.

I'd try the numpy mailing list:

http://www.scipy.org/Mailing_Lists

Alright. I will try that.


> 5) In principal Python can divide those numbers (2.3e-28)/(5.6e-6)**3

I get half the result you suggest above:

>>> (2.3e-28)/(5.6e-6)**3
1.3096756559766764e-12

which agrees with my HP-48GX, and the result after simplifying by hand 
to 2.3e-10/175.616. So I think that is the correct result, not 2.6e-12.

You are totally right. I forgot to write down a factor of 2. I am so sorry
about it!! 

> My source code is attached. Please keep in mind that I just started
> programing and Python is my first Language. I tried to do my best to
> comment every single step to make the code readable. Here it comes:

Comments are good, but too many comments hurt readability. Don't feel 
that you need to comment every single line. Comments like:

x = x+1  # increment x by 1

are just noise. But this is a good comment:

x = x+1  # add correction for wind-chill factor.


> self.m = 39.96*1.66*10**(-27)                    #m is the mass
> of a single trapped ion in the chain

I wonder why you calculate m with an explicit exponentiation operator, 
instead of a floating point exponent?

The difference is very small, so it probably doesn't matter:

>>> 39.96*1.66*10**(-27)
6.63336006e-26
>>> 39.96*1.66e-27
6.63335994e-26

Haha, you are right. Thats just because I am a physicist and used to write
it down that way. I changed that!


>  for i in range(len(x)):
>  for j in range(len(x)):
>  if j >i:
>  Vx = Vx + C * (abs(x[i]-x[j]))**(-1)#then we
> add the coulomb interaction

You can simplify that nested loop and addition:

for i in range(len(x)):
for j in range(i+1, len(x)):
Vx += C * (abs(x[i]-x[j]))**(-1)  # add the coulomb interaction


The function range takes up to three integer arguments:

range(start, end, step)

where start and step are optional, defaulting to 0 and 1 respectively. 
By starting the inner loop at i+1, you guarantee that j is always > i 
and therefore you can skip the test.

The other change is that instead of 

Vx = Vx + something

you can write:

Vx += something

Thanks. I got it. In the beginning it is just hard to see every
simplification. But I understand what you were suggesting and I corrected
it. Sometimes a program evolves also physically. So I added the while loop
because I found out later that I need it. 



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



-- 
View this message in context: 
http://old.nabble.com/-Tutor--problems-with-numdifftools-tp30034615p30060567.html
Sent from the Python - tutor mailing list archive at Nabble.com.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor