Re: [Tutor] subprocess output

2010-07-28 Thread Sander Sweers
- Original message -
> I'm using Python 2.6.5 and I've got a challenge with the subprocess
> module. I'd like the output to be stored in a variable, and not sent to
> the stdout. The relevant lines as they are now:

Go to google, enter "pymotw subprocess" and hit I am feeling lucky ;-)

greets
Sander

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


Re: [Tutor] subprocess output

2010-07-28 Thread Evert Rol
> #!/usr/bin/env python
> import subprocess
> import sys
> 
> dom = sys.argv[1]
> switch = sys.argv [2]
> answer = subprocess.call("whois " + dom, shell=True)
> 
> Execute the above (whatever.py -example.com -a1) prints the entire WHOIS
> output, but I just want it saved to the variable 'answer', nothing more.

create a subprocess.Popen object instead, and use communicate().
Use subprocess.PIPE for the stdout and stderr arguments (and use a list for the 
executable + arguments: ["whois", dom], leaving out the shell argument).
Read the library docs: see example 17.1.3.2.


> Changing 'shell=True' to 'shell=False' raises an exception and removing
> the 'shell=' altogether is troublesome as well.

shell=False is the default

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


Re: [Tutor] Running .py files in shell

2010-07-28 Thread Kevin Rapley



I am running Mac OSX v10.6.4 Snow Leopard
I am running Python 2.6.1

In general get the MacPython distributions of Python etc, they usually
install easier (ie from the GUI) than the "Unix" based versions.

Okay, thanks. I will look into that.

1. How do I execute .py files in the command line shell? I have my
files in /Users/Kevin/python-exercises/ and am opening python in
shell from that directory

There are numerous ways, especially in MacOS.
The simplest way is to put a "shebang" line at the top of your script
and then make them executable:

$ cat>  myscript.py
What is the significance of this and how do I use it? I guess this is a 
command to add in to Shell, however when I use this I get the following 
error:


>>> cat > tryme1.py
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'cat' is not defined

#! /bin/env python

With my configuration, I am guessing I need to change this snippet to:

#! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python

# the above line must be the first line in your file and tells the
# shell where to find python
# rest of your code follows.

Then use chmod +x to make it executable

$ chmod +x myscript.py

When I try to run this with one of my files I get the following error:

>>> chmod +x tryme1.py
  File "", line 1
chmod +x tryme1.py
  ^
SyntaxError: invalid syntax

Now you can run it:

$ myscript.py

Alternatively you can just call python explicitly:

$ python myscript.py

I get a syntax error doing this too:

>>> python tryme1.py
  File "", line 1
python tryme1.py
^
SyntaxError: invalid syntax
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running .py files in shell

2010-07-28 Thread David Hutto
On Wed, Jul 28, 2010 at 2:39 AM, Kevin Rapley  wrote:
>
>>> I am running Mac OSX v10.6.4 Snow Leopard
>>> I am running Python 2.6.1
>>
>> In general get the MacPython distributions of Python etc, they usually
>> install easier (ie from the GUI) than the "Unix" based versions.
>
> Okay, thanks. I will look into that.
>>>
>>> 1. How do I execute .py files in the command line shell? I have my
>>> files in /Users/Kevin/python-exercises/ and am opening python in
>>> shell from that directory
>>
>> There are numerous ways, especially in MacOS.
>> The simplest way is to put a "shebang" line at the top of your script
>> and then make them executable:
>>
>> $ cat>  myscript.py
>
> What is the significance of this and how do I use it? I guess this is a
> command to add in to Shell, however when I use this I get the following
> error:
>
 cat > tryme1.py
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'cat' is not defined
>>
>> #! /bin/env python
>
> With my configuration, I am guessing I need to change this snippet to:
>
> #! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python
>>
>> # the above line must be the first line in your file and tells the
>> # shell where to find python
>> # rest of your code follows.
>>
>> Then use chmod +x to make it executable
>>
>> $ chmod +x myscript.py
>
> When I try to run this with one of my files I get the following error:
>
 chmod +x tryme1.py
>  File "", line 1
>    chmod +x tryme1.py
>                  ^
> SyntaxError: invalid syntax
>>
>> Now you can run it:
>>
>> $ myscript.py
>>
>> Alternatively you can just call python explicitly:
>>
>> $ python myscript.py
>
> I get a syntax error doing this too:
>
 python tryme1.py
>  File "", line 1
>    python tryme1.py
>                ^
> SyntaxError: invalid syntax
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

It looks like you're trying to type it into the python prompt, when
you should be trying to type it into the shell command prompt. You can
import tryme1.py in the python shell/interpreter, but you python
tryme.py from the shell
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Order Of Operations Question

2010-07-28 Thread David Hutto
From a practice exercise in Building Skills In Python page 64 I'm
working on How Much Does The Atmosphere Weigh? Part 1:
To check it states that the answer should be app. 10**18kg However,
and I've checked to make sure that the math I've layed out matches up
with the texts, I get 5.07360705863e+20

In the code I have broken the order of operations down to more
parenthetical, and tried outright, but see nothing obvious about how
it's strung together. If anyone has had a similar experience with the
problem given, or see anything blatantly obvious I've done wrong with
the ordering of operations. I tried to include as much of the
problem(formulas are just above variables they're used in) as comments
as possible.

import math
def atmosphereWeight():
pi = math.pi
"""Air Pressure (at sea level) P0. This is the long-term average.
P0 = 1.01325 × 10**5"""
airPressCLevl = 1.01325*(10**5)
gravity = 9.82
"""We can use g to get the kg of mass from the force of air
pressure P0. Apply the acceleration of gravity
(in m/sec2) to the air pressure (in kg · m/sec2). This result is
mass of the atmosphere in kilograms per
square meter (kg/m2).
Mm2 = P0 × g"""
masAtmoInKgPerSqM = airPressCLevl * gravity
"""Given the mass of air per square meter, we need to know how
many square meters of surface to apply
this mass to. Radius of Earth R in meters, m. This is an average
radius; our planet isn’t a perfect sphere.
R = 6.37 × 10"""
avgRadiusEarth = 6.37 * (10**6)
"""The area of a Sphere.
A = 4πr2"""
areaSphere = 4 * pi * (avgRadiusEarth**2)
"""Mass of atmosphere (in Kg) is the weight per square meter,
times the number of square meters
Ma = P0 × g × A"""
masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere
print(masEarthAtmoInKgPerSqM)

atmosphereWeight()


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


Re: [Tutor] Calculating and returning possible combinations of elements from a given set

2010-07-28 Thread ZUXOXUS
2010/7/28 Dave Angel 

>
>
> ZUXOXUS wrote:
>
>> Oh, I think i got it:
>>
>>
>>
>>> for prod in itertools.product('ABC', 'ABC'):
>
>
 print(prod)
>>
>> ('A', 'A')
>> ('A', 'B')
>> ('A', 'C')
>> ('B', 'A')
>> ('B', 'B')
>> ('B', 'C')
>> ('C', 'A')
>> ('C', 'B')
>> ('C', 'C')
>>
>> Thank you very much!!
>>
>> 2010/7/28 ZUXOXUS 
>>
>>
> You're top-posting, which loses all the context. In this forum, put your
> comments after whatever lines you're quoting.
>
> Your latest version gets the product of two.  But if you want an arbitrary
> number, instead of repeating the iterable ('ABC' in your case), you can use
> a repeat count.  That's presumably what you were trying to do in your
> earlier incantation.  But you forgot the 'repeat' keyword:
>
> for prod in itertools.product('ABC', repeat=4):
>   
>
> will give you all the four-tuples.
>
> DaveA
>
>
>

> Hey
>

Sorry for the top-posting, I forgot this rule

Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Evert Rol
Sorry, forgot to reply-to-all:


I don't know the book nor the exercise, but see my comments interspersed in the 
code, and a few general remarks at the bottom

> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20
> 
> In the code I have broken the order of operations down to more
> parenthetical, and tried outright, but see nothing obvious about how
> it's strung together. If anyone has had a similar experience with the
> problem given, or see anything blatantly obvious I've done wrong with
> the ordering of operations. I tried to include as much of the
> problem(formulas are just above variables they're used in) as comments
> as possible.
> 
> import math
> def atmosphereWeight():
>   pi = math.pi
>   """Air Pressure (at sea level) P0. This is the long-term average.
>   P0 = 1.01325 × 10**5"""
>   airPressCLevl = 1.01325*(10**5)
>   gravity = 9.82
>   """We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>   (in m/sec2) to the air pressure (in kg · m/sec2). This result is
> mass of the atmosphere in kilograms per
>   square meter (kg/m2).
>   Mm2 = P0 × g"""
>   masAtmoInKgPerSqM = airPressCLevl * gravity

Simply from looking at the units left and right of the equality sign, you'll 
need to *divide* by g, not multiply: [kg] = [kg m / s^2] / [m / s^2]


>   """Given the mass of air per square meter, we need to know how
> many square meters of surface to apply
>   this mass to. Radius of Earth R in meters, m. This is an average
> radius; our planet isn’t a perfect sphere.
>   R = 6.37 × 10"""
>   avgRadiusEarth = 6.37 * (10**6)
>   """The area of a Sphere.
>   A = 4πr2"""
>   areaSphere = 4 * pi * (avgRadiusEarth**2)
>   """Mass of atmosphere (in Kg) is the weight per square meter,
> times the number of square meters
>   Ma = P0 × g × A"""
>   masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere

ditto here: divide by gravity, not multiply by it.


>   print(masEarthAtmoInKgPerSqM)
> 
> atmosphereWeight()


Few general remarks:
- the standard way of writing numbers with a power of ten in code is something 
like 1.01325e5. I guess this is also easier/quicker to execute (not that this 
code is time-critical, but in general)
- why do you assign masTmoInKgPerSqM, then later not use it when calculating 
masEarthAtmoInKgPerSqM?
- just use math.pi when calculating areaSphere, instead of "pi = math.pi" and 
then later using pi. For me, that's just as clear.
- no need to put parentheses around powers; they are evaluated before the 
multiplication (unless this is what you meant by "to more parenthetical"
- try indenting the comments as well; more readable

Probably not all of the above are necessary, if you wrote this for debugging 
your problem, but they're just some thoughts that occurred to me.

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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Hugo Arts
On Wed, Jul 28, 2010 at 11:41 AM, David Hutto  wrote:
> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20
>

Either there is an error in the texts, or you have not checked
throughly enough. It goes wrong here:

>"""We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>(in m/sec2) to the air pressure (in kg · m/sec2). This result is
> mass of the atmosphere in kilograms per
>square meter (kg/m2).
>Mm2 = P0 × g"""
>masAtmoInKgPerSqM = airPressCLevl * gravity

The Air pressure is in Pascal, which is kg / (m*s^2), not (kg * m)/s^2
as you state. That is the Newton. Pascal can also be written as
Newton/m^2, which is (M*g)/m^2. So to get mass per square meter, you
should divide by the acceleration g, not multiply.

With that modification I get about 5e18, which seems correct.

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


[Tutor] problem with simple script

2010-07-28 Thread Richard D. Moores
I have a practical need for a script that will give me a random int in the
closed interval [n, m]. Please see .

This works fine when I enter both n and m as, for example, "23, 56", or even
"56, 23". But often the closed interval is [1, m], so I'd like to not have
to enter the 1 in those cases, and just enter, say, "37" to mean the
interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it
fails. This seems like it should be so simple to do, but it isn't not for
me. Advice, please.

Thanks,

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


Re: [Tutor] problem with simple script

2010-07-28 Thread Luke Paireepinart
Just do a split of the input from the user on space or comma. If Len() of the 
split data is 1, do your [1, ...] interval, otherwise do the other interval.

Sent from my iPhone

On Jul 28, 2010, at 6:51 AM, "Richard D. Moores"  wrote:

> I have a practical need for a script that will give me a random int in the 
> closed interval [n, m]. Please see .
> 
> This works fine when I enter both n and m as, for example, "23, 56", or even 
> "56, 23". But often the closed interval is [1, m], so I'd like to not have to 
> enter the 1 in those cases, and just enter, say, "37" to mean the interval 
> [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it fails. This 
> seems like it should be so simple to do, but it isn't not for me. Advice, 
> please.
> 
> Thanks, 
> 
> Dick Moores
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with simple script

2010-07-28 Thread Nick Raptis

On 07/28/2010 02:51 PM, Richard D. Moores wrote:
I have a practical need for a script that will give me a random int in 
the closed interval [n, m]. Please see 
.


This works fine when I enter both n and m as, for example, "23, 56", 
or even "56, 23". But often the closed interval is [1, m], so I'd like 
to not have to enter the 1 in those cases, and just enter, say, "37" 
to mean the interval [1, 37]. Highlighted lines 9-11 are my attempt to 
do this, but it fails. This seems like it should be so simple to do, 
but it isn't not for me. Advice, please.


Thanks,

Dick Moores
   

Split the input before the if.
Fork based on the length of the resulting list.
:)

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


[Tutor] String replace question

2010-07-28 Thread Rod
Hello,

I need to replace a period (.) in a domain name with a slash period (\.).

I'm attempting to use the string replace method to do this.

Example:

uri = domain.com

uri.replace('.', '\.')

This returns 'domain\\.com'

Is there a way to do this so there is not a double slash before the period?

Thanks for any help,
Rod
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String replace question

2010-07-28 Thread Rod
> Try
 print uri.replace('.', '\.')
> and you'll find the replacement works fine.
>
> Or write the output to file, and look at the file.
>
> Python shows a representation on its prompt, and thus needs to escape the 
> backslash (by prepending another backslash). Otherwise you might think '\.' 
> was meant, which is simply a '.'.
> But consider:
 uri.replace('.', '\n')
> 'domain\ncom'
 print uri.replace('.', '\n')
> domain
> com
>
> because '\n' is really a different string (character) than a backslash + 'n'.


Thanks, that was very helpful. I was using the interactive interpreter
to test things.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String replace question

2010-07-28 Thread Nick Raptis

On 07/28/2010 03:41 PM, Rod wrote:

Hello,

I need to replace a period (.) in a domain name with a slash period (\.).

I'm attempting to use the string replace method to do this.

Example:

uri = domain.com

uri.replace('.', '\.')

This returns 'domain\\.com'


   
Of course it does! Try to print the value. Now the extra backslash is 
gone. Confused yet?


Well, the backslash is an escape character in Python and other languages 
too. It's used for special characters like newlines ( \n ).
But then how can you enter just a backslash by itself? Easy, escape it 
with a backslash. So \ becomes '\\'


The representation under your uri.replace() line reflects that (escaped) 
syntax.

When you're printing it though, you see the string as you meant it to.

So, nothing is wrong with your lines of code , there's only one 
backslash there, it just get's represented as two.


In fact, you should have escaped \. your self writing the line as such:
uri.replace('.', '\\.')
but since \. is not a special character, python is smart enough to not mind

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


Re: [Tutor] Calculating and returning possible combinations of elements from a given set

2010-07-28 Thread Dave Angel

ZUXOXUS wrote:

2010/7/28 Dave Angel 


Your latest version gets the product of two.  But if you want an arbitrary
number, instead of repeating the iterable ('ABC' in your case), you can use
a repeat count.  That's presumably what you were trying to do in your
earlier incantation.  But you forgot the 'repeat' keyword:

for prod in itertools.product('ABC', repeat=4):
  

will give you all the four-tuples.

DaveA






Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!

  
Since you're new to Python, it's probably useful to expound a little 
bit, on how you could have figured it out from the help documentation.


itertools.product(/*iterables/[, /repeat/])

   Cartesian product of input iterables.

   Equivalent to nested for-loops in a generator expression. For
   example, product(A, B) returns the same as ((x,y) for x in A for y
   in B).

   The nested loops cycle like an odometer with the rightmost element
   advancing on every iteration. This pattern creates a lexicographic
   ordering so that if the input’s iterables are sorted, the product
   tuples are emitted in sorted order.

   To compute the product of an iterable with itself, specify the
   number of repetitions with the optional /repeat/ keyword argument.
   For example, product(A, repeat=4) means the same as product(A, A, A, A).



Now that example at the end is exactly what you need here. But let's 
look at the first line.


See the *iterables in the formal parameter list. The leading * means you 
can put 1, 2, or as many iterables as you like, and they'll each be 
treated as an independent dimension in the cartesian product. So when 
you put the arguments,

...product("ABC", 2)

the 2 is treated as an iterable, which it isn't. Thus your error. When 
there are an arbitrary number of such arguments, followed by another 
optional parameter, there's no way the compiler could guess in which 
sense you wanted the 2 to be used. So you have to use that parameter's 
name as a keyword in your call. If you have a function declared as

def product(*iterables, repeat):
.

then you can call it with
count = 4
product(list1, list2, repeat=count)

and by specifying the 'repeat' keyword, the system knows to stop copying 
your arguments into the iterables collection.


Actually, I suspect that if you specify a repeat count, you can only 
supply one iterable, but I'm really talking about the language here.


DaveA




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


Re: [Tutor] problem with simple script

2010-07-28 Thread Steven D'Aprano
On Wed, 28 Jul 2010 09:51:40 pm Richard D. Moores wrote:
> I have a practical need for a script that will give me a random int
> in the closed interval [n, m]. Please see
> .

What is the purpose of this function?

def get_random_int(n, m):
return randint(n, m)

Why call "get_random_int" instead of randint? It does *exactly* the same 
thing, only slower because of the extra indirection.

If the only reason is because you don't like the name randint, then the 
simple solution is this:

get_random_int = randint

Now get_random_int is another name for the same function, without any 
indirection.


> This works fine when I enter both n and m as, for example, "23, 56",
> or even "56, 23". But often the closed interval is [1, m], so I'd
> like to not have to enter the 1 in those cases, and just enter, say,
> "37" to mean the interval [1, 37]. 

Keep the front end (user interface) separate from the back end. Here's 
the back end:

def get_random_int(n, m=None):
if m is None:  # only one argument given
n, m = 1, n
return randint(n, m)

def str_to_bounds(s):
L = s.split(',', 1)  # Split a maximum of once.
return [int(x) for x in L]


And here's the front end:

def get_interval_bounds():
print("Get a random integer in closed interval [n, m]")
s = input("Enter n, m: ")
return str_to_bounds(s)

def main():
prompt = "Enter 'q' to quit; nothing to get another random int: "
while True:
args = get_interval_bounds()
print(get_random_int(*args))
ans = input(prompt)
if ans == 'q':
print("Bye.") 
# Waiting 2 seconds is not annoying enough, 
# waiting 2.2 seconds is too annoying.
sleep(2.1)  # Just annoying enough!
return

main()


Hope this helps!



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


[Tutor] Plugin system - how to manage plugin files?

2010-07-28 Thread Mac Ryan
Hi everybody,

This is more of a python software design question rather than a
question on the Python syntax alone. I hope it is fine to ask here.

I am working on a small project, that I will release under a GPL
license, whose main design guiding principle is extensibility. Thus I am
trying to make as easy as possible for other devs to create plugins.

I implemented my plugin system by defining a metaclass, that register -
with a class method - the class name of any plugin that gets loaded (all
plugins inherit from a class defined in the core code). Basically this
means that a developer will have to define his class as:

class PluginMyName(MotherOfAllPlugins)
do_stuff_here

And the main program will know of his presence because "PluginMyName"
will be included in the list available at "MotherOfAllPlugins.plugins".

Being the mounting method a class method, all plugins get registered
when their class code is loaded into memory (so even before an object of
that class is instantiated).

The system works good enough for me (although I am always open to
suggestions on how to improve the architecture!) but I am now wondering
what would be the best way to manage the plugin files (i.e. where and
how the files containing the plugins should be stored).

So far I am using - for developing purposes - a package that I called
"plugins". I put all my pluginX.py files in the package directory and I
simply have to issue "import plugins" in the main.py file, for all the
plugins to get mounted properly. However this system is only good while
I am developing and testing the code, as:
1. Plugins might come with their own unittests, and I do not want to
load those in memory.
2. All plugins are currently loaded into memory, but indeed there are
certain plugins which are alternative versions of the same feature, so
you really just need to know that you can switch between the two, but
you want to load into memory just one.
3. At some point, I will want to have a double location for installing
plugins: a system-wide location (for example /usr/local/bin/) and a
user-specific one (for example /home//.myprogram/).

So my questions are really - perhaps - three:

1) What is the most sensible format for the plugin code (a file? a
package? A simple directory of files?)
2) Which is a smart way to use Python introspection to recognise the
presence of plugins without necessarily loading (importing) them.
3) Is there a standard way / best practice (under gnu/linux, at least)
to allow for plugins to be placed in two different locations?

Thank you in advance for your time and guidance,
Mac.

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


Re: [Tutor] problem with simple script

2010-07-28 Thread Richard D. Moores
On Wed, Jul 28, 2010 at 04:51, Richard D. Moores  wrote:
> I have a practical need for a script that will give me a random int in the
> closed interval [n, m]. Please see .
>
> This works fine when I enter both n and m as, for example, "23, 56", or even
> "56, 23". But often the closed interval is [1, m], so I'd like to not have
> to enter the 1 in those cases, and just enter, say, "37" to mean the
> interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it
> fails. This seems like it should be so simple to do, but it isn't not for
> me. Advice, please.

While waiting for replies (they were there, but I had screwed up the
Gmail filter for them and they missed the inbox), I thought I'd just
avoid the need to split, and enter n and m separately. I also added
the ability to get another random int in the same closed interval,
without reentering n and m.

See this effort at .

Now I'll dig into all the help I received. I see an *args in Steven's
detailed reply. That'll take some reviewing to understand.

Thanks VERY much!

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


[Tutor] Problem with input() and unicode string

2010-07-28 Thread Alex
Hello, I have a problem with this code:

# -*- coding: latin-1 -*-
year = u'año, ò, ó, ç'
print year
year = input(u'Introduce el año:')
print year
raw_input()

The first print statement works as expected, both in IDLE and when 
double-clicking the file for a console view.
The second one works in IDLE, but just flashes by when double-clicking the 
file, 
due to an error report I can't see. 

I believe the problem is that input prompt doesn't support unicode strings, 
which means I can't use my language for prompts?
Could someone please tell me how to fix it or provide a workaround?
Thanx.

Using Python 2.7 under win32.


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


Re: [Tutor] Calculating and returning possible combinations of elements from a given set

2010-07-28 Thread ZUXOXUS
>
> 2010/7/28 Dave Angel 
> 
>
> Your latest version gets the product of two.  But if you want an arbitrary
>> number, instead of repeating the iterable ('ABC' in your case), you can
>> use
>> a repeat count.  That's presumably what you were trying to do in your
>> earlier incantation.  But you forgot the 'repeat' keyword:
>>
>> for prod in itertools.product('ABC', repeat=4):
>>  
>>
>> will give you all the four-tuples.
>>
>> DaveA
>>
>>
>>
>>
>
> 
>
> Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
>
>
>
Since you're new to Python, it's probably useful to expound a little bit, on
how you could have figured it out from the help documentation.

itertools.product(/*iterables/[, /repeat/])

  Cartesian product of input iterables.

  Equivalent to nested for-loops in a generator expression. For
  example, product(A, B) returns the same as ((x,y) for x in A for y
  in B).

  The nested loops cycle like an odometer with the rightmost element
  advancing on every iteration. This pattern creates a lexicographic
  ordering so that if the input’s iterables are sorted, the product
  tuples are emitted in sorted order.

  To compute the product of an iterable with itself, specify the
  number of repetitions with the optional /repeat/ keyword argument.
  For example, product(A, repeat=4) means the same as product(A, A, A, A).



Now that example at the end is exactly what you need here. But let's look at
the first line.

See the *iterables in the formal parameter list. The leading * means you can
put 1, 2, or as many iterables as you like, and they'll each be treated as
an independent dimension in the cartesian product. So when you put the
arguments,
...product("ABC", 2)

the 2 is treated as an iterable, which it isn't. Thus your error. When there
are an arbitrary number of such arguments, followed by another optional
parameter, there's no way the compiler could guess in which sense you wanted
the 2 to be used. So you have to use that parameter's name as a keyword in
your call. If you have a function declared as
def product(*iterables, repeat):
.

then you can call it with
count = 4
product(list1, list2, repeat=count)

and by specifying the 'repeat' keyword, the system knows to stop copying
your arguments into the iterables collection.

Actually, I suspect that if you specify a repeat count, you can only supply
one iterable, but I'm really talking about the language here.

DaveA



Wow, Thank you DaveA, that was very useful.

However, as it usually happens, answers trigger new questions.

My doubt now is whether I can change the way python show the combinations.

I mean, here's what python actually does:

>>> for prod in itertools.product('abc', repeat=3):
print(prod)

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
[...] etc.


what if I want the combinations listed in a... well, in a list, kind of like
this:

('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)

can I do that?

I have checked how the function works (see below), perhaps I have to just
change couple of lines of the code and voilá, the result displayed as I
want... But unfortunately I'm too newbie for this, or this is too hardcore:

def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)


Any ideas will be very much appreciated.

2010/7/28 Dave Angel 

> ZUXOXUS wrote:
>
>> 2010/7/28 Dave Angel 
>> 
>>
>>  Your latest version gets the product of two.  But if you want an
>>> arbitrary
>>> number, instead of repeating the iterable ('ABC' in your case), you can
>>> use
>>> a repeat count.  That's presumably what you were trying to do in your
>>> earlier incantation.  But you forgot the 'repeat' keyword:
>>>
>>> for prod in itertools.product('ABC', repeat=4):
>>>  
>>>
>>> will give you all the four-tuples.
>>>
>>> DaveA
>>>
>>>
>>>
>>>
>>
>> 
>>
>> Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
>>
>>
>>
> Since you're new to Python, it's probably useful to expound a little bit,
> on how you could have figured it out from the help documentation.
>
> itertools.product(/*iterables/[, /repeat/])
>
>   Cartesian product of input iterables.
>
>   Equivalent to nested for-loops in a generator expression. For
>   example, product(A, B) returns the same as ((x,y) for x in A for y
>   in B).
>
>   The nested loops cycle like an odometer with the rightmost element
>   advancing on every iteration. This pattern creates a lexicographic
>   ordering so that if the input’s iterables are sorted, the product
>   tuples are emitted in sorted order.
>
>   To compute the product of an iterable with itself, specify the
>   number of repetitions with the optional /repeat/ keyword 

[Tutor] Newbie question - syntax - BeautifulSoup

2010-07-28 Thread Tommy Kaas
I have just begun a struggle learning Python. I have read most of "Beginning
Python - from Novice to Professional" - and some of it I even understood J

This is my first question to the list. And I'm sure not the last.

 

I'm especially interested in learning web scraping techniques and here:
http://stackoverflow.com/questions/2081586/web-scraping-with-python I found
a small example:

 

import urllib2 

from BeautifulSoup import BeautifulSoup 

 

soup =
BeautifulSoup(urllib2.urlopen('http://www.timeanddate.com/worldclock/astrono
my.html?n=78').read()) 

 

for row in soup('table', {'class' : 'spad'})[0].tbody('tr'): 

  tds = row('td') 

  print tds[0].string, tds[1].string 

  # will print date and sunrise

 

 

 

The example works fine, and I can change it a bit and it still works. But I
simply don't understand how I am supposed to the fourth line - after "for
row in soup". I can clearly see it defines the area I want to scrape, but
how is the syntax build? And almost as important - where should I have found
that information myself? I have tried to read the help-file of
BeautifulSoup, but found nothing there.

 

Thanks in advance.

 

 

Tommy Kaas

Journalist

Kaas & Mulvad

 

Copenhagen, Denmark

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


Re: [Tutor] Problem with input() and unicode string

2010-07-28 Thread Timo

On 28-07-10 18:05, Alex wrote:

Hello, I have a problem with this code:
# -*- coding: latin-1 -*-
year = u'año, ò, ó, ç'
print year
year = input(u'Introduce el año:')
print year
raw_input()
The first print statement works as expected, both in IDLE and when 
double-clicking the file for a console view.
The second one works in IDLE, but just flashes by when double-clicking 
the file, due to an error report I can't see.
I don't have a solution, but call your script from the commandline to 
stay open after exceptions. Or try some things in the Python interactive 
prompt:


>>> year = input(u'Introduce el año:')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in 
position 14: ordinal not in range(128)


Cheers,
Timo


I believe the problem is that input prompt doesn't support unicode 
strings, which means I can't use my language for prompts?

Could someone please tell me how to fix it or provide a workaround?
Thanx.
Using Python 2.7 under win32.


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


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


Re: [Tutor] Problem with input() and unicode string

2010-07-28 Thread Huy Ton That
You can do:

input(unicode('Introduce el año:', 'latin-1').encode('latin-1'))

Maybe someone could explain it better than I can.

HTH,

Huy

On Wed, Jul 28, 2010 at 12:05 PM, Alex  wrote:

> Hello, I have a problem with this code:
>
> # -*- coding: latin-1 -*-
> year = u'año, ò, ó, ç'
> print year
> year = input(u'Introduce el año:')
> print year
> raw_input()
>
> The first print statement works as expected, both in IDLE and when
> double-clicking the file for a console view.
> The second one works in IDLE, but just flashes by when double-clicking the
> file, due to an error report I can't see.
> I believe the problem is that input prompt doesn't support unicode strings,
> which means I can't use my language for prompts?
> Could someone please tell me how to fix it or provide a workaround?
> Thanx.
>
> Using Python 2.7 under win32.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running .py files in shell

2010-07-28 Thread Alan Gauld

"Kevin Rapley"  wrote

The simplest way is to put a "shebang" line at the top of your 
script

and then make them executable:

$ cat>  myscript.py

What is the significance of this and how do I use it?



>>> cat > tryme1.py


Notice the difference in the prompt. A dollar sign is the generic
way of indicating a Unix shell prompt.

cat is a Unix command which catenates the output to a file, again 
using
cat like this is a generic way of sayong create a file containing 
whatever
follows cat. In practice you would use a text editor like vim or pico 
etc.





means the python prompt. You are typing a Unix command into Python
which doesn't reciognise it, hence the error.

My apologies for not being explicit. I assumed since you were using
the shell to run sudo port install that you were an experienced Unix
shell user and would understand the significance of $.

(Incidentally % is the generic way of indicating a rioot user command,
so

% cat > mydfile

implies login as root (or use sudo) to type the command)


Then use chmod +x to make it executable

$ chmod +x myscript.py
When I try to run this with one of my files I get the following 
error:


>>> chmod +x tryme1.py


Same problem. chmod is the unix command to Change Mode of a file.


$ myscript.py

Alternatively you can just call python explicitly:

$ python myscript.py

I get a syntax error doing this too:

>>> python tryme1.py


And again, you type python on its own to start a Python interpreter 
session.
You type, in Unix shell, python file.py to get Python to execute 
file.py


You can find a box explaining some of this in my tutor in the Style 
topic,

near the bottom...

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Calculating and returning possible combinations ofelements from a given set

2010-07-28 Thread Alan Gauld


"ZUXOXUS"  wrote


My doubt now is whether I can change the way python show the 
combinations.


Python will display the compbinations however you tell it to.
The function generates the combinations the display is up to you.
In this case you are simply printing the results as they come.
But you can put them in a list if you prefer.


prodList = []
for prod in itertools.product('abc', repeat=3):

...   prodList.append(prod)
...

print prodList


You can manipulate prod however you like before putting it inthe list.
Once you have the list you can sort that list to get anyorder you 
want.

And once you have your soted and formatted list you can print it out
using whatever formatting you want.

It is always good to separate the generation of data fropm the
storage of data from the display of data.

I have checked how the function works (see below), perhaps I have to 
just
change couple of lines of the code and voilá, the result displayed 
as I
want... But unfortunately I'm too newbie for this, or this is too 
hardcore:


Its hardly ever a good idea to modify the standard library functions.
You can write a wrapper around them if you like - and indeed thats 
normal.

But changing them is almost always a very bad  idea!

def myProduct(*args, **kwds):
# do something with input data
# call itertools.product(args, kwds)
# do something with the output
# return a result

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Alan Gauld


"David Hutto"  wrote


To check it states that the answer should be app. 10**18kg However,
and I've checked to make sure that the math I've layed out matches 
up

with the texts, I get 5.07360705863e+20


A couple of comments but my Physics is a bit rusty!!


import math
def atmosphereWeight():
   pi = math.pi
   """Air Pressure (at sea level) P0. This is the long-term average.
   P0 = 1.01325 × 10**5"""


You can express scientific notaton directly:


   airPressCLevl = 1.01325*(10**5)


airPressCLevl = 1.01325e5


   gravity = 9.82


It was 9.81 when I was at school.
Doubt if that accounts for the difference though...



   """We can use g to get the kg of mass from the force of air
pressure P0. Apply the acceleration of gravity
   (in m/sec2) to the air pressure (in kg · m/sec2).


I'd expect pressure to be in Pa or N/m2 or (Kg*m/s2)/m2 = Kg/ms2?


mass of the atmosphere in kilograms per
   square meter (kg/m2).
   Mm2 = P0 × g"""
   masAtmoInKgPerSqM = airPressCLevl * gravity


So I'd expect P0/g?


   """Given the mass of air per square meter, we need to know how
many square meters of surface to apply
   this mass to. Radius of Earth R in meters, m. This is an average
radius; our planet isn’t a perfect sphere.
   R = 6.37 × 10"""
   avgRadiusEarth = 6.37 * (10**6)


I assume the comment's exponent is wrong?! :-)


   """The area of a Sphere.
   A = 4πr2"""
   areaSphere = 4 * pi * (avgRadiusEarth**2)



   """Mass of atmosphere (in Kg) is the weight per square meter,
times the number of square meters
   Ma = P0 × g × A"""



   masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere


Why don't you use the value you calculated above?

Now if you divide by 10 instead of multiplying by 10 you get a
different of 2 in the exponent?


   print(masEarthAtmoInKgPerSqM)


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Calculating and returning possible combinations ofelements from a given set

2010-07-28 Thread ZUXOXUS
2010/7/28 Alan Gauld 

>
> "ZUXOXUS"  wrote
>
>
>
>  My doubt now is whether I can change the way python show the combinations.
>>
>
> Python will display the compbinations however you tell it to.
> The function generates the combinations the display is up to you.
> In this case you are simply printing the results as they come.
> But you can put them in a list if you prefer.
>
>  prodList = []

 for prod in itertools.product('abc', repeat=3):

>>> ...   prodList.append(prod)
> ...
>
>> print prodList

>>>
> You can manipulate prod however you like before putting it inthe list.
> Once you have the list you can sort that list to get anyorder you want.
> And once you have your soted and formatted list you can print it out
> using whatever formatting you want.
>
> It is always good to separate the generation of data fropm the
> storage of data from the display of data.
>
>
>  I have checked how the function works (see below), perhaps I have to just
>> change couple of lines of the code and voilá, the result displayed as I
>> want... But unfortunately I'm too newbie for this, or this is too
>> hardcore:
>>
>
> Its hardly ever a good idea to modify the standard library functions.
> You can write a wrapper around them if you like - and indeed thats normal.
> But changing them is almost always a very bad  idea!
>
> def myProduct(*args, **kwds):
># do something with input data
># call itertools.product(args, kwds)
># do something with the output
># return a result
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Hi Alan and everybody

Well, that is not exactly what I expected, but can help

>>> lista = []
>>> for prod in itertools.product('aei', repeat=2):
lista.append(prod)
print(lista)

[('a', 'a')]
[('a', 'a'), ('a', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a'), ('i', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a'), ('i', 'e'), ('i', 'i')]
>>>


Now I only need to put together in a single string all the elements that are
grouped in parentheses, I think I can do that

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


Re: [Tutor] Problem with input() and unicode string

2010-07-28 Thread Alan Gauld


"Alex"  wrote


The first print statement works as expected, both in IDLE and when
double-clicking the file for a console view.
The second one works in IDLE, but just flashes by when 
double-clicking the file,

due to an error report I can't see.


So run it from a Console prompt and you will then be able to see the 
error.

That should help you debug it.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Newbie question - syntax - BeautifulSoup

2010-07-28 Thread Alan Gauld


"Tommy Kaas"  wrote


for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):

The example works fine, and I can change it a bit and it still 
works. But I
simply don't understand how I am supposed to the fourth line - after 
"for
row in soup". I can clearly see it defines the area I want to 
scrape, but

how is the syntax build?


Do you understand the syntax from a Python point of view?


that information myself? I have tried to read the help-file of
BeautifulSoup, but found nothing there.


Which help file?
There is a fairly good tutorial for Beautiful Soup here:

http://www.crummy.com/software/BeautifulSoup/documentation.html

Is that the one you meant?

Did you find the section "Searching By CSS class"?

If so we need more specific questionws about what you don't 
understand.

If not, try reading it and then come back for more... :-)

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Calculating and returning possible combinations of elements from a given set

2010-07-28 Thread Dave Angel

ZUXOXUS wrote:


My doubt now is whether I can change the way python show the combinations.

I mean, here's what python actually does:

  

for prod in itertools.product('abc', repeat=3):


print(prod)

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
[...] etc.


what if I want the combinations listed in a... well, in a list, kind of like
this:

('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)

can I do that?

I have checked how the function works (see below), perhaps I have to just
change couple of lines of the code and voilá, the result displayed as I
want... But unfortunately I'm too newbie for this, or this is too hardcore:

def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)


Any ideas will be very much appreciated.


Well itertools.product() already returns an iterator that's equivalent 
to a list of tuples.   You can print that list simply by doing something 
like:

print list(itertools.product('abc', repeat=3))

So your question is how you can transform such a list into a list of 
strings instead.


so try each of the following.

for prod in itertools.product('abc', repeat=3):
   print "".join(prod)

print ["".join(prod) for prod in itertools.product('abc', repeat=3)]

DaveA


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


Re: [Tutor] Plugin system - how to manage plugin files?

2010-07-28 Thread Scott Nelson
On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan  wrote:

> Hi everybody,
>
>
Mac,

I don't know if this is exactly what you are after, but I created a
poor-man's plugin system by simply putting .py files into the same directory
as my app and naming them like _plugin.py  Each of these .py "plugins",
had to define a class named "Plugin" that had some set of expected methods
and properties (ex: initialize(), run(), etc.).  Then, when my app started
up, it simply got a list of all the "*_plugin.py" files in the current
directory, dynamically imported the files using "my_module =
__import__(name)" and then I could do whatever I wanted with that module
using "my_module", such as instantiate an object for each module's "Plugin"
class, etc.

Actually, here's a snippet of code I had lying around that I slapped
together a few years ago to remind myself of how I did this.  I can't
promise this is 100% tested, but it should give you an idea.

http://pastebin.com/UtVp6J9j

Also, you might want to look at this discussion:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/

Best of luck!

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


Re: [Tutor] Newbie question - syntax - BeautifulSoup

2010-07-28 Thread Tommy Kaas
-Oprindelig meddelelse-
Fra: tutor-bounces+tommy.kaas=kaasogmulvad...@python.org
[mailto:tutor-bounces+tommy.kaas=kaasogmulvad...@python.org] På vegne af
Alan Gauld
Sendt: 28. juli 2010 20:00
Til: tutor@python.org
Emne: Re: [Tutor] Newbie question - syntax - BeautifulSoup


"Tommy Kaas"  wrote

> for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
>
> The example works fine, and I can change it a bit and it still 
> works. But I
> simply don't understand how I am supposed to the fourth line - after 
> "for
> row in soup". I can clearly see it defines the area I want to 
> scrape, but
> how is the syntax build?

Do you understand the syntax from a Python point of view?

No. That's the problem.


> that information myself? I have tried to read the help-file of
> BeautifulSoup, but found nothing there.

Which help file?

Well, maybe not a file, but the text produced by typing: help(BeautifulSoup)



There is a fairly good tutorial for Beautiful Soup here:

http://www.crummy.com/software/BeautifulSoup/documentation.html

Is that the one you meant?

Did you find the section "Searching By CSS class"?

If so we need more specific questionws about what you don't 
understand.
If not, try reading it and then come back for more... :-)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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

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


[Tutor] A Django Beginner View Question

2010-07-28 Thread Alasdair Macmillan
Hi

I am building my first Django site which has a lot of effectively 'static' 
pages where I just want to make the meta data and text editable.

The model is

models.py

class About(models.Model):
page_title = models.CharField(max_length=900, help_text='Text at top of 
browser window')
meta_keywords = models.CharField(max_length=900, help_text='Keywords (for 
SEO)')
meta_description = models.CharField(max_length=160, help_text='Description 
(for SEO)')
logo_header = models.CharField(max_length=900, help_text='H1 Header (for 
SEO)')
header = models.CharField(max_length=60)
body = models.TextField()
last_updated = models.DateTimeField(default=datetime.datetime.now, 
primary_key=True)

class Meta:
get_latest_by = "last_updated"
verbose_name_plural = "About Page"
#managed = False

def __unicode__(self):
return self.title


I'm trying to understand how to either write a model that only allows a single 
entry or write a view that will take either a single entry or the most recent 
entry.

views.py

def about(request):
return render_to_response('about.html',
{ 'About' : 
About.objects.latest() })
urls.py

(r'^about/$', 'harkproject.cms.views.about'),

Much appreciated
Al Macmillan



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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread David Hutto
On Wed, Jul 28, 2010 at 6:11 AM, Evert Rol  wrote:
> Sorry, forgot to reply-to-all:
>
>
> I don't know the book nor the exercise, but see my comments interspersed in 
> the code, and a few general remarks at the bottom
>
>> From a practice exercise in Building Skills In Python page 64 I'm
>> working on How Much Does The Atmosphere Weigh? Part 1:
>> To check it states that the answer should be app. 10**18kg However,
>> and I've checked to make sure that the math I've layed out matches up
>> with the texts, I get 5.07360705863e+20
>>
>> In the code I have broken the order of operations down to more
>> parenthetical, and tried outright, but see nothing obvious about how
>> it's strung together. If anyone has had a similar experience with the
>> problem given, or see anything blatantly obvious I've done wrong with
>> the ordering of operations. I tried to include as much of the
>> problem(formulas are just above variables they're used in) as comments
>> as possible.
>>
>> import math
>> def atmosphereWeight():
>>   pi = math.pi
>>   """Air Pressure (at sea level) P0. This is the long-term average.
>>   P0 = 1.01325 × 10**5"""
>>   airPressCLevl = 1.01325*(10**5)
>>   gravity = 9.82
>>   """We can use g to get the kg of mass from the force of air
>> pressure P0. Apply the acceleration of gravity
>>   (in m/sec2) to the air pressure (in kg · m/sec2). This result is
>> mass of the atmosphere in kilograms per
>>   square meter (kg/m2).
>>   Mm2 = P0 × g"""
>>   masAtmoInKgPerSqM = airPressCLevl * gravity
>
> Simply from looking at the units left and right of the equality sign, you'll 
> need to *divide* by g, not multiply: [kg] = [kg m / s^2] / [m / s^2]
>
>
>>   """Given the mass of air per square meter, we need to know how
>> many square meters of surface to apply
>>   this mass to. Radius of Earth R in meters, m. This is an average
>> radius; our planet isn’t a perfect sphere.
>>   R = 6.37 × 10"""
>>   avgRadiusEarth = 6.37 * (10**6)
>>   """The area of a Sphere.
>>   A = 4πr2"""
>>   areaSphere = 4 * pi * (avgRadiusEarth**2)
>>   """Mass of atmosphere (in Kg) is the weight per square meter,
>> times the number of square meters
>>   Ma = P0 × g × A"""
>>   masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere
>
> ditto here: divide by gravity, not multiply by it.
>
>
>>   print(masEarthAtmoInKgPerSqM)
>>
>> atmosphereWeight()
>
>
> Few general remarks:
> - the standard way of writing numbers with a power of ten in code is 
> something like 1.01325e5. I guess this is also easier/quicker to execute (not 
> that this code is time-critical, but in general)

I'll probably ending up reading something about it later in the book,
but as a quick question, why does:

>>> 5e18 == 5**18
False
>>> int(5e18) == int(5**18)
False
>>> 1.01325e5 == 1.01325**5
False

> - why do you assign masTmoInKgPerSqM, then later not use it when calculating 
> masEarthAtmoInKgPerSqM?

I turned all of the formulas given into a variables, however in
masEarthAtmoInKgPerSqM it would have been neater to use
masTmoInKgPerSqM * areaSphere, instead of reusing the two variables
again in .masEarthAtmoInKgPerSqM.


> - just use math.pi when calculating areaSphere, instead of "pi = math.pi" and 
> then later using pi. For me, that's just as clear.
> - no need to put parentheses around powers; they are evaluated before the 
> multiplication (unless this is what you meant by "to more parenthetical"

Yes, it was just to break it into smaller, more readable, pieces.

> - try indenting the comments as well; more readable

It looked better when color coded in the editor, but not here in black
and white.

>
> Probably not all of the above are necessary, if you wrote this for debugging 
> your problem, but they're just some thoughts that occurred to me.
>
> Enjoy your calculations.

Will the 'fun' never end?
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread David Hutto
On Wed, Jul 28, 2010 at 6:19 AM, Hugo Arts  wrote:
> On Wed, Jul 28, 2010 at 11:41 AM, David Hutto  wrote:
>> From a practice exercise in Building Skills In Python page 64 I'm
>> working on How Much Does The Atmosphere Weigh? Part 1:
>> To check it states that the answer should be app. 10**18kg However,
>> and I've checked to make sure that the math I've layed out matches up
>> with the texts, I get 5.07360705863e+20
>>
>
> Either there is an error in the texts, or you have not checked
> throughly enough. It goes wrong here:
>
>>    """We can use g to get the kg of mass from the force of air
>> pressure P0. Apply the acceleration of gravity
>>    (in m/sec2) to the air pressure (in kg · m/sec2). This result is
>> mass of the atmosphere in kilograms per
>>    square meter (kg/m2).
>>    Mm2 = P0 × g"""
>>    masAtmoInKgPerSqM = airPressCLevl * gravity
>
> The Air pressure is in Pascal, which is kg / (m*s^2), not (kg * m)/s^2
> as you state. That is the Newton. Pascal can also be written as
> Newton/m^2, which is (M*g)/m^2. So to get mass per square meter, you
> should divide by the acceleration g, not multiply.

In the initial email I did forget this part:
Pressure is measured in Newtons, N, kg m/sec2. Air Pressure is is
measured in Newtons of force per square meter, N/m2.

Which might  have been a more informed question. I was trying not to
add in the whole question, and place the pieces in, but apparently
forgot one.
>
> With that modification I get about 5e18, which seems correct.

I get this with yours and Evert's modification from mult to div, but
if you're right, then the 10e18 the book states as a checker is a
typo/error.

Thanks, for your replies, I'll redo the example again, with a little
more sleep this time. Don't really need to know atmospheric pressure
right now, but might endup at wikipedia/google later.
>
> Hugo
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Eike Welk
Hello David!

On Thursday July 29 2010 01:00:15 David Hutto wrote:

> but as a quick question, why does:
> >>> 5e18 == 5**18
> 
> False

5e18 is a short form of a somewhat complex term:

5e18 == 5 * 10**18 == 500


But 5**18 is just the exponentiation operator:

5**18 == 3814697265625


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


Re: [Tutor] Plugin system - how to manage plugin files?

2010-07-28 Thread Mac Ryan
On Wed, 2010-07-28 at 13:53 -0500, Scott Nelson wrote:
> On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan 
> wrote:
> Hi everybody,
> 
> 
> Mac,
> 
> I don't know if this is exactly what you are after, but I created a
> poor-man's plugin system by simply putting .py files into the same
> directory as my app and naming them like _plugin.py  Each of
> these .py "plugins", had to define a class named "Plugin" that had
> some set of expected methods and properties (ex: initialize(), run(),
> etc.).  Then, when my app started up, it simply got a list of all the
> "*_plugin.py" files in the current directory, dynamically imported the
> files using "my_module = __import__(name)" and then I could do
> whatever I wanted with that module using "my_module", such as
> instantiate an object for each module's "Plugin" class, etc.
> 
> Actually, here's a snippet of code I had lying around that I slapped
> together a few years ago to remind myself of how I did this.  I can't
> promise this is 100% tested, but it should give you an idea.
> 
> http://pastebin.com/UtVp6J9j
> 
> Also, you might want to look at this discussion:
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/
> 
> Best of luck!
> 
> -Scott

Thank you Scott for your reply,

I inspected the code you pastebin'd, but I am under the impression the
solution you proposed present about the same shortcomings that mines... 

I recognise that the naming convention of files solve the problem of
having in the same place files which might not be plugins, but the
naming convention is an imposition that I would rather try not to impose
to other devs, the reson being that in my application plugins get
subclassed, so that - if the name of the plugin must be relevant - names
would end up being something like:

   medianvalues_gtk_statistics_scores_plugin.py 

where "medianvalues" would be the name of the plugin, an each other
underscore-separated word would be a parent class.

My hope is that somebody will show me some "automagic obscure voodoo
method" (I am thinking to some "__real_vooodoo__" method or function
somewhere in the module file or in the __init__.py file of the packages)
that will be able to provide information on the plugin without actually
loading it...

Let's see if somebody else will reply to this [admittedly
not-so-popular] thread! ;)

Mac.

PS: About the thread that you linked in your reply: my solution is in
the line of what Fredrik Lundh proposed, using __metaclass___

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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Hugo Arts
On Thu, Jul 29, 2010 at 1:10 AM, David Hutto  wrote:
> I get this with yours and Evert's modification from mult to div, but
> if you're right, then the 10e18 the book states as a checker is a
> typo/error.
>

Wait.. in your original e-mail you said the answer as given by the
book was 10**18, not 10e18 (which is of course 10 * 10**18). But
either way, I'd consider 5e18 a correct answer, since it's fairly
close to 1e18 (relatively anyway, it's still 5 times as big). At least
there is not an order of magnitude difference anymore.

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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread David Hutto
On Wed, Jul 28, 2010 at 7:35 PM, Hugo Arts  wrote:
> On Thu, Jul 29, 2010 at 1:10 AM, David Hutto  wrote:
>> I get this with yours and Evert's modification from mult to div, but
>> if you're right, then the 10e18 the book states as a checker is a
>> typo/error.
>>
>
> Wait.. in your original e-mail you said the answer as given by the
> book was 10**18,

It is 10**18, in the book, (no e)that was before Eike informed me it
was not the same as 10e18. I stated this after
you used e, and before Eike explained, so I was using 10e18 in the
reply thinking of it as as 10**18.

not 10e18 (which is of course 10 * 10**18). But
> either way, I'd consider 5e18 a correct answer, since it's fairly
> close to 1e18 (relatively anyway, it's still 5 times as big). At least
> there is not an order of magnitude difference anymore.
>
> Hugo
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question - syntax - BeautifulSoup

2010-07-28 Thread Alan Gauld

"Tommy Kaas"  wrote


> > for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
>
>Do you understand the syntax from a Python point of view?

No. That's the problem.



OK, I'll assume you understand the basic for loop structure
and focus on the function call:

soup('table', {'class' : 'spad'})[0].tbody('tr')

Ignore the bit at the end for now:

soup('table', {'class' : 'spad'})

Thats a call to a function taking a string and a dictionary as 
arguments.
The string says we want to look for table tags. And the dictionary 
says

we want tables that have an attribute class with a value spad.
Is that bit clear?

Then we add an index [0] to get the first table.

Finally we call tbody("tr") to extract the tr tags from the table.
The for loop thus iterates over the rows of the first table with 
class=spad.


There might be slightly more to it than that, its a long time since I
played with BS...


Which help file?
Well, maybe not a file, but the text produced by typing: 
help(BeautifulSoup)


Ah, in that case you should definitely read the tutorial.

http://www.crummy.com/software/BeautifulSoup/documentation.html

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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

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


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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Dave Angel



David Hutto wrote:


I'll probably ending up reading something about it later in the book,
but as a quick question, why does:

  

5e18 =5**18


False
  

int(5e18) =int(5**18)


False
  

1.01325e5 =1.01325**5


False

  
The  999e44  notation is intended to be similar to scientific notation, 
where 44 is the exponent, in base 10.


So redoing your equalities:

5e18 == 5*(10**18)
int(5e18) == int(5 * 10**18)
1.01325e5 == 1.01325 * 10**5

The extra parens in the first case, and the extra spaces in the others, are 
just for readability.  It'd be just as correct to say:
1.01325e5 == 1.01325*10**5

DaveA


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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread David Hutto
On Wed, Jul 28, 2010 at 8:03 PM, Dave Angel  wrote:
>
>
> David Hutto wrote:
>>
>> 
>> I'll probably ending up reading something about it later in the book,
>> but as a quick question, why does:
>>
>>
>
> 5e18 =5**18
>
>>
>> False
>>
>
> int(5e18) =int(5**18)
>
>>
>> False
>>
>
> 1.01325e5 =1.01325**5
>
>>
>> False
>>
>>
>
> The  999e44  notation is intended to be similar to scientific notation,
> where 44 is the exponent, in base 10.
>
> So redoing your equalities:
>
> 5e18 == 5*(10**18)
> int(5e18) == int(5 * 10**18)
> 1.01325e5 == 1.01325 * 10**5
>
> The extra parens in the first case, and the extra spaces in the others, are
> just for readability.  It'd be just as correct to say:
> 1.01325e5 == 1.01325*10**5
>
> DaveA
>
>
>

Already done!

And 5.3*10**18 or 5.2613095377e+18 is the appropriate answer from a
quick google search that resulted in the rounded 5.3e18. So the book
apparently left out the 5.3*, and just gave 10**18.

Thanks for your help, I think this is solved.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with input() and unicode string

2010-07-28 Thread Mark Tolonen


"Alan Gauld"  wrote in message 
news:i2pqps$fp...@dough.gmane.org...


"Alex"  wrote


The first print statement works as expected, both in IDLE and when
double-clicking the file for a console view.
The second one works in IDLE, but just flashes by when double-clicking 
the file,

due to an error report I can't see.


So run it from a Console prompt and you will then be able to see the 
error.

That should help you debug it.


Try:

   import sys
   year = raw_input(u'Introduce el año:'.encode(sys.stdout.encoding))

Without the explicit encoding I got a UnicodeError due to using the 'ascii' 
codec.


Interesting that 'print' uses the console encoding for Unicode strings, but 
input() and raw_input() don't for their prompts.


You may still get a Unicode error if your console encoding doesn't support 
the characters you are trying to print, but it worked on my US Windows 
'cp437' console.


-Mark


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


[Tutor] Python Help - How to end program

2010-07-28 Thread Jason MacFiggen
Python keeps looping when it gets past the int 0, how do I end the program
when it the int 0 or > 0.

my_hp = 50
mo_hp = 50
my_dmg = random.randrange(1, 20)
mo_dmg = random.randrange(1, 20)
endProgram = end()
while True:
if mo_hp < 0:
print "The Lich King has been slain!"
elif my_hp < 0:
print "You have been slain by the Lich King!"
if mo_hp <= 0:
endProgram
else my_hp <= 0:
endProgram
else:
print "Menu Selections: "
print "1 - Attack"
print "2 - Defend"
print
choice = input ("Enter your selection. ")
choice = float(choice)
print
if choice == 1:
mo_hp = mo_hp - my_dmg
print "The Lich King is at ", mo_hp, "Hit Points"
print "You did ", my_dmg, "damage!"
print
my_hp = my_hp - mo_dmg
print "I was attacked by the lk for ", mo_dmg," damage!"
print "My Hit Points are ", my_hp
print
elif choice == 2:
mo_hp = mo_hp - my_dmg / 2
print "The Lich King is at", mo_hp, "Hit Points"
print "you did ", my_dmg / 2, "damage!"
print
my_hp = my_hp - mo_dmg
print "I was attacked by the lk for ", mo_dmg," damage!"
print "My Hit Points are ", my_hp
print
-Thank you
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help - How to end program

2010-07-28 Thread Benjamin Castillo
Jason
 
Are you trying to prevent negative numbers?
 
Ben

--- On Wed, 7/28/10, Jason MacFiggen  wrote:


From: Jason MacFiggen 
Subject: [Tutor] Python Help - How to end program
To: tutor@python.org
Date: Wednesday, July 28, 2010, 9:01 PM



Python keeps looping when it gets past the int 0, how do I end the program when 
it the int 0 or > 0.
 
my_hp = 50
    mo_hp = 50
    my_dmg = random.randrange(1, 20)
    mo_dmg = random.randrange(1, 20)
    endProgram = end()
    while True:
    if mo_hp < 0:
    print "The Lich King has been slain!"
    elif my_hp < 0:
    print "You have been slain by the Lich King!"
    if mo_hp <= 0:
    endProgram
    else my_hp <= 0:
    endProgram
    else:
    print "Menu Selections: "
    print "1 - Attack"
    print "2 - Defend"
    print
    choice = input ("Enter your selection. ")
    choice = float(choice)
    print
    if choice == 1:
    mo_hp = mo_hp - my_dmg
    print "The Lich King is at ", mo_hp, "Hit Points"
    print "You did ", my_dmg, "damage!"
    print
    my_hp = my_hp - mo_dmg
    print "I was attacked by the lk for ", mo_dmg," damage!"
    print "My Hit Points are ", my_hp
    print
    elif choice == 2:
    mo_hp = mo_hp - my_dmg / 2
    print "The Lich King is at", mo_hp, "Hit Points"
    print "you did ", my_dmg / 2, "damage!"
    print
    my_hp = my_hp - mo_dmg
    print "I was attacked by the lk for ", mo_dmg," damage!"
    print "My Hit Points are ", my_hp
    print

-Thank you
-Inline Attachment Follows-


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



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


Re: [Tutor] Python Help - How to end program

2010-07-28 Thread Mark Tolonen


"Jason MacFiggen"  wrote in message 
news:aanlktinevw8zje7fxktomks+tbrp=trmb7sb7pbkt...@mail.gmail.com...

Python keeps looping when it gets past the int 0, how do I end the program
when it the int 0 or > 0.

my_hp = 50
   mo_hp = 50
   my_dmg = random.randrange(1, 20)
   mo_dmg = random.randrange(1, 20)
   endProgram = end()
   while True:
   if mo_hp < 0:
   print "The Lich King has been slain!"
   elif my_hp < 0:
   print "You have been slain by the Lich King!"
   if mo_hp <= 0:
   endProgram
   else my_hp <= 0:
   endProgram
   else:
   print "Menu Selections: "
   print "1 - Attack"
   print "2 - Defend"
   print
   choice = input ("Enter your selection. ")
   choice = float(choice)
   print
   if choice == 1:
   mo_hp = mo_hp - my_dmg
   print "The Lich King is at ", mo_hp, "Hit Points"
   print "You did ", my_dmg, "damage!"
   print
   my_hp = my_hp - mo_dmg
   print "I was attacked by the lk for ", mo_dmg," damage!"
   print "My Hit Points are ", my_hp
   print
   elif choice == 2:
   mo_hp = mo_hp - my_dmg / 2
   print "The Lich King is at", mo_hp, "Hit Points"
   print "you did ", my_dmg / 2, "damage!"
   print
   my_hp = my_hp - mo_dmg
   print "I was attacked by the lk for ", mo_dmg," damage!"
   print "My Hit Points are ", my_hp
   print


The keyword 'break' will exit a while loop.  Since you have no commands 
after the while loop, that will end your program.


-Mark


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