Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Rich Lovely
2009/7/4 Angus Rodgers :
>>Date: Sat, 04 Jul 2009 13:26:12 +0100
>>From: Angus Rodgers 
>>Message-ID: 

> My response to this [but see the afterthought below!] is that I
> definitely need to put into the documentation string something
> like "*** THIS FUNCTION IS HIGHLY VULNERABLE TO A MALICIOUS USER
> ***", so that I will be strongly warned NEVER to incorporate it
> into any program that might be used by anyone other than myself.
>
> It might also be a good idea to include some kind of brief warning
> in the user prompts. (This won't put off a malicious user, of course,
> but it would help to keep me in mind of the potential danger.)

I personally would never release code to any sort of public calling
eval on user-inputted (or even user-accessible) strings or using
input(), even if you had to go through fifteen different dialogue
boxes first (see below).  Also, at a beginner level, as soon as you
can manage without these, you should, perhaps even going so far as to
delete the old function, so you never run the risk of copy and pasting
when not paying much attention.

There are always ignorant users, who can influenced by malicious
users, and might not know what I mentioned in my previous is wrong,
therefore making warnings irrelevant.  To give a classic example, as
seen in IRC channels across the web:

 How do I do XYZ in ABC?
 NewUser: Press Alt+F4 if you're on windows.
 Thanks.
#NewUser has quit - connection reset by peer#
Later...
#NewUser has joined the channel#
 Everytime I try to do XYZ, my IRC client shuts down.
 NewUser: What command are you using?
 CodeChimp: Alt+F4
 lol
 NewUser: That's a common problem.  You can fix it in the
config screen.  Bring it up by holding down Ctrl and Alt, and pressing
Del twice quickly.
 ok
#NewUser has quit - connection reset by peer#
 lol

Perhaps I enjoyed writing that a little too much... and I could easily
go on.  But I won't.  Email me for the continuing saga of NewUser.

Anyone at a level to need to use input() appropriatly is usually
capable of writing their own script to do so, and would probably just
be annoyed at any warnings you chose to stick in.  I've never gotten
to the point where I've needed input(). I'm curious to know whether
anyone on the list has.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading variables in a data set?

2009-07-04 Thread Emile van Sebille

On 7/4/2009 9:09 AM Steven Buck said...

Dear Python Tutor,
I'm doing econometric work and am a new user of Python. I have read 
several of the tutorials, but haven't found them useful for a newbie 
problem I've encountered.
I've used a module (StataTools) from (http://presbrey.mit.edu/PyDTA ) to 
get a Stata ".dta" file into Python. In Stata the data set is an NXK 
matrix where N is the number of observations (households) and K is the 
number of variables. 
I gather it's now a list where each element of the list is an 
observation (a vector) for one household.  The name of my list is 
"data"; I gather Python recognizes the first observation by: data[1] . 
Example,
data = [X_1, X_2, X_3, . . . . , X_N]  where each X_i for all i, is 
vector of household characteristics, eg X_1 = (age_1, wage_1, . . . , 
residence_1).
 
I also have a list for variable names called "varname"; although I'm not 
sure the module I used to extract the ".dta" into Python also created a 
correspondence between the varname list and the data list--the python 
interpreter won't print anything when I type one of the variable names, 
I was hoping it would print out a vector of ages or the like. 


Assuming you're working in the python console somewhat from the example 
on the source website for PyDTA:


from PyDTA import Reader
dta = Reader(file('input.dta'))
fields = ','.join(['%s']*len(dta.variables()))

... you might try starting at dir|help (dta.variables)

I didn't look, but the sources are available as well.


 
In anycase, I'd like to make a scatter plot in pylab, 


I think I'd use dictionaries along these lines:

  wages = { age_1: [ X_1, X_15, X_3...],
age_2: [ X_2, X_5... ],
  ]


but don't know how 
to  identify a variable in "data" (i.e.  I'd like a vector listing the 
ages and another vector listing the wages of  households).  


I think poking into dta.variables will answer this one.

HTH,

Emile

Perhaps, I 
need to run subroutine to collect each relevant data point to create a 
new list which I define as my variable of interest?  From the above 
example, I'd like to create a list such as: age = [age_1, age_2, . . . , 
age_N] and likewise for wages.
 
Any help you could offer would be very much appreciated.  Also, this is 
my first time using the python tutor, so let me know if I've used it 
appropriately or if I should change/narrow the structure of my question.
 
Thanks

Steve

--
Steven Buck
Ph.D. Student
Department of Agricultural and Resource Economics
University of California, Berkeley




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading variables in a data set?

2009-07-04 Thread Luke Paireepinart

Pardon me, I don't have time to address all of your questions; however,
Steven Buck wrote:
I gather it's now a list where each element of the list is an 
observation (a vector) for one household.  The name of my list is 
"data"; I gather Python recognizes the first observation by: data[1] .
No, the first item in a list is going to be data[0], not data[1].  
Python counts from 0 not 1.  Unless by the "first observation" you mean 
the "one after the zeroth observation" but that is not the common usage 
of that term.

Example,
data = [X_1, X_2, X_3, . . . . , X_N]  where each X_i for all i, is 
vector of household characteristics, eg X_1 = (age_1, wage_1, . . . , 
residence_1).
 
I also have a list for variable names called "varname"; although I'm 
not sure the module I used to extract the ".dta" into Python also 
created a correspondence between the varname list and the data 
list--the python interpreter won't print anything when I type one of 
the variable names, I was hoping it would print out a vector of ages 
or the like.
It should output whatever is contained in the variable, if you're at the 
interpreter.  Sounds like you're not getting your data in.

>>> x = ["hello", "world!", 42]
>>> x
['hello', 'world!', 42]

Hope that helps a litttle bit, good luck!
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Alan Gauld

"Angus Rodgers"  wrote


You can miss out a few else clauses, especially after
the try/excepts:

---
while get_bool("Continue?"):
   try: key = eval(raw_input("Key value of type " + key_typ.__name__ + 
": "))

   except StandardError: print "That's not a Python expression!"

   if not isinstance(key, key_typ):
  print "That's not a value of type", key_typ.__name__ else: # User 
has provided
   try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": 
"))

   except StandardError: print "That's not a Python expression!"


I don't see this, because, if an exception does occur, won't
there be an attempt to access one of the objects 'key', 'val'
before it has been assigned?


There will, which will throw another exception and exit.
And the exception will tell you which try failed, which is
more than your generic printed error message does...

Sometimes just letting Python fail is the best course.
Of course your messages will be prettier than the standard
stacktrace, but less useful for debugging.

However you can get what you want without the else by
simply inserting a break in each exception handler, which
keeps the indentation under control.

while get_bool("Continue?"):
   try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": 
"))

   except StandardError:
   print "That's not a Python expression!"
   break

   if not isinstance(key, key_typ):
  print "That's not a value of type", key_typ.__name__ else: # User 
has provided

  etc...

HTH,

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



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Angus Rodgers
>Date: Sat, 4 Jul 2009 19:52:56 +0100
>From: "Alan Gauld" 
>Message-ID: 
>
>You can miss out a few else clauses, especially after 
>the try/excepts:
>
>---
>while get_bool("Continue?"): 
>try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": ")) 
>except StandardError: print "That's not a Python expression!" 
>
>if not isinstance(key, key_typ): 
>   print "That's not a value of type", key_typ.__name__ else: # User has 
> provided
>try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": ")) 
>except StandardError: print "That's not a Python expression!" 
>
>if not isinstance(val, val_typ): 
>   print "That's not an object of type", val_typ.__name__ 
>else: # User has provided an object of the correct type 
>   ans[key] = val 
>return ans
>

I don't see this, because, if an exception does occur, won't
there be an attempt to access one of the objects 'key', 'val'
before it has been assigned?

Not that this matters in the largely rewritten "Version 0.1":
   (retention: 1 day)

(Is it time for me to get into the comfy chair yet?)  8-P
-- 
Angus Rodgers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] reading variables in a data set?

2009-07-04 Thread Steven Buck
 Dear Python Tutor,
I'm doing econometric work and am a new user of Python. I have read several
of the tutorials, but haven't found them useful for a newbie problem I've
encountered.
I've used a module (StataTools) from (http://presbrey.mit.edu/PyDTA ) to get
a Stata ".dta" file into Python. In Stata the data set is an NXK matrix
where N is the number of observations (households) and K is the number of
variables.
I gather it's now a list where each element of the list is an observation (a
vector) for one household.  The name of my list is "data"; I gather Python
recognizes the first observation by: data[1] .
Example,
data = [X_1, X_2, X_3, . . . . , X_N]  where each X_i for all i, is vector
of household characteristics, eg X_1 = (age_1, wage_1, . . . , residence_1).

I also have a list for variable names called "varname"; although I'm not
sure the module I used to extract the ".dta" into Python also created a
correspondence between the varname list and the data list--the python
interpreter won't print anything when I type one of the variable names, I
was hoping it would print out a vector of ages or the like.

In anycase, I'd like to make a scatter plot in pylab, but don't know how to
identify a variable in "data" (i.e.  I'd like a vector listing the ages and
another vector listing the wages of  households).  Perhaps, I need to run
subroutine to collect each relevant data point to create a new list which I
define as my variable of interest?  From the above example, I'd like to
create a list such as: age = [age_1, age_2, . . . , age_N] and likewise for
wages.

Any help you could offer would be very much appreciated.  Also, this is my
first time using the python tutor, so let me know if I've used it
appropriately or if I should change/narrow the structure of my question.

Thanks
Steve

-- 
Steven Buck
Ph.D. Student
Department of Agricultural and Resource Economics
University of California, Berkeley
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stack unwind using exceptions.

2009-07-04 Thread Kent Johnson
On Sat, Jul 4, 2009 at 3:56 PM, Noufal Ibrahim wrote:
> Hello everyone,
>
> Would it be considered unorthodox or 'wrong' in some sense for me to use an
> exception to unwind the stack and return to a caller for a recursive
> function?
>
> I need to do a depth first search and when I find the right element to just
> stop the whole thing, and get back to the caller saying that I found it.

Why not just return the value from the function and pass it up the
call chain? If a call fails return None. Something like this:

def search(self, value):
  if self.value == value:
return self

  for child in self.children:
result = child.search(value)
if result is not None:
  return result

  return None

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Lie Ryan
Angus Rodgers wrote:
>> Date: Sat, 04 Jul 2009 13:26:12 +0100
>> From: Angus Rodgers 
>> Message-ID: 
>>
>>    (retention: 1 day)
> 
> This is just a quick(ish!) response to the feedback so far.
> 
> I realise, now, that I should have quoted what the exercise in the
> book was asking for, to explain why my code is more elaborate than
> the minimum that would be required to solve the problem at hand.
> 
>>From the book (2nd ed., p. 151):
> 
>  "[...] we recommend that the reader convert his or her code to
>  functions that can be used in future exercises."
> 
> This requirement was uppermost in my mind.

If it is the top requirement, then your code is not general enough as it
can only ask for dictionaries. A general solution would be at least
something like this: (now talk about bloat and overdesigning...)

#!/usr/bin/env python

import re
from functools import partial

''' Like Swiss Army. It does everything.
Includes batteries and kitchen sink.
Caveat: written at 3AM in the morning.
'''

class PromptError(Exception): pass

def prompt(prompt='? ',
   reprompt='Invalid input. Try again.',
   validate=str,
   postprocess=str,
   tries=3,
   catchlist=(ValueError,),
  ):
''' prompt the user for input, validate, and return the result
postprocess is called before returning the value
if number of tries exceeds `tries` raise PromptError. Set
tries to -1 to prompt infinitely
'''
while tries != 0:
inp = raw_input(prompt)
try:
validate(inp)
except catchlist, e:
print reprompt
tries -= 1
else:
return postprocess(inp)
else:
raise PromptError('Maximum number of tries exceeded')

def expecting(s, expected=[], errmess='Invalid input'):
''' return True if `s` matches any regex pattern in `expected`
raises ValueError otherwise.
'''
for pat in expected:
if re.compile(pat+'$', re.IGNORECASE).match(s):
return True
else:
raise ValueError(errmess)

def convert(s, convtab):
''' convert `s` into convtab's key '''
for target, pats in convtab.iteritems():
for pat in pats:
if re.compile(pat+'$', re.IGNORECASE).match(s):
return target
else:
raise ValueError('Cannot convert')

def chain(*rings):
''' Calls a list of function and return their
return values as a tuple
'''
def _chain():
return tuple(ring() for ring in rings)
return _chain

def serial_prompt(mainprompt,
  cont_prompt='Continue? ',
  postprocess=lambda x: x,
 ):
''' Prompts for a series of values, with 'continue?'s
between each prompt.
Return values of the prompts are collected in a list
and passed to `postprocess`.
'''
def _serial_prompt():
ret = [mainprompt()]
while get_bool(cont_prompt):
ret.append(mainprompt())
return postprocess(ret)
return _serial_prompt

trues = ['1', 'ye?s?', 'tr?u?e?']
falses = ['0', 'no?', 'fa?l?s?e?']
bools = trues + falses
expecting_bool = partial(expecting, expected=bools)
convert_bool = partial(convert, convtab={True: trues, False: falses})
get_bool = partial(prompt,
   validate=expecting_bool,
   postprocess=convert_bool,
  )

get_key = prompt
get_value = partial(prompt,
validate=int,
postprocess=int,
   )
get_kv = chain(partial(get_key, prompt='key (str): '),
   partial(get_value, prompt='value (int): '),
  )

get_dict = serial_prompt(get_kv, postprocess=dict)

print get_bool('bool: ')
print get_key('key (str): ')
print get_value('value (int): ')
print get_kv()
print get_dict()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Stack unwind using exceptions.

2009-07-04 Thread Noufal Ibrahim

Hello everyone,

Would it be considered unorthodox or 'wrong' in some sense for me to use 
an exception to unwind the stack and return to a caller for a recursive 
function?


I need to do a depth first search and when I find the right element to 
just stop the whole thing, and get back to the caller saying that I 
found it.



TIA.

--
~noufal
http://nibrahim.net.in/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Alan Gauld

"Angus Rodgers"  wrote

>  (i) trapping the exception StandardError may, for all I know,
> be a daft thing to do;

Not daft but not that common. Mainly because use of eval() 
is kind of frownedoon for security reasons. (See below.)

> (iv) correlatively with (iii), my indentation perhaps looks a
> little extreme (perhaps suggesting a redesign, I don't know);

You can miss out a few else clauses, especially after 
the try/excepts:

---
while get_bool("Continue?"): 
try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": ")) 
except StandardError: print "That's not a Python expression!" 

if not isinstance(key, key_typ): 
   print "That's not a value of type", key_typ.__name__ else: # User has 
provided
try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": ")) 
except StandardError: print "That's not a Python expression!" 

if not isinstance(val, val_typ): 
   print "That's not an object of type", val_typ.__name__ 
else: # User has provided an object of the correct type 
   ans[key] = val 
return ans


I'm hoping you know about the security issues around using 
eval with raw_input? The use can input any valid python code 
and it will be evaluated! For experimenting its OK but in 
live code it would be very risky.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Angus Rodgers
>Date: Sat, 04 Jul 2009 13:26:12 +0100
>From: Angus Rodgers 
>Message-ID: 
>
>   (retention: 1 day)

This is just a quick(ish!) response to the feedback so far.

I realise, now, that I should have quoted what the exercise in the
book was asking for, to explain why my code is more elaborate than
the minimum that would be required to solve the problem at hand.

>From the book (2nd ed., p. 151):

 "[...] we recommend that the reader convert his or her code to
 functions that can be used in future exercises."

This requirement was uppermost in my mind.

I also remembered from previous brushes with programming (mostly
decades ago) that it is handy to have a little function that asks
a question and won't quit until the user gives a yes-or-no answer.

On the other hand, it would be overkill to try to write a program
that applies a full lexical, syntactic, and semantic analysis to
the text input by the user in an interactive console session.  In
the future I am quite likely to want to write something like that
(essentially reviving a student project from 1990, on which I got
a good enough mark to pass the course, but which suggested many
lines of further development - and whose implementation as my first
largish C++ program was simply abominable!), or else to use it
off-the-shelf from some Python library or other (suggestions?), 
but it would take months to write (perhaps weeks in Python, or
years in C++ ...), and therefore is out of the question here.

So I tried to take the middle course of writing small functions
that would be of use to me in future exercises (whether in this
book or elsewhere). The whole thing only took me an hour or so
to write (I didn't time the work, but it was certainly a matter
of minutes, rather than hours), so it wasn't overkill (I think!).

I did consider writing simpler code for input of strings as key
values, and, in a rewrite, I think I will provide such simpler
code, for this frequently-occurring default case (while still
allowing for general key types).

I also belatedly realised that I was stupidly duplicating code
in my get_dict() function, and I will rewrite this, as Daniel 
Woodhouse suggests.  get_dict() should make two calls to some
function with a name like get_val(), with a general type as a
parameter (perhaps defaulting to str - although the value type
parameter of get_dict() should, on reflection, have no default).

>--
>
>Date: Sat, 4 Jul 2009 18:50:48 +0300
>From: Daniel Woodhouse 
>Message-ID:
>   <4c0a037d0907040850r7874313cn4abacc7db5957...@mail.gmail.com>
>
>I had a look at your code, and refactored it a bit.  See my modifications at
>http://python.pastebin.com/m50acb143 You'll noticed I removed one of your
>functions completely (it was unnecessary) and the get_dict() function is not
>so heavily nested.

(See comments above.  I agree with the last bit, at least!)

>Some ideas:
>raw_input returns a string, so we can safely assume its a string.

It's definitely a good idea to treat this frequently-occurring
simple special case using simpler code (if only so that the user
doesn't have to enter those annoying quotation marks every time).

>Whether or
>not its a valid name for a student is a different matter, and if you wish to
>check such things you may wish to look at the regular expression module
>(re).

I'll certainly be investigating regular expressions (later), but
I think you'll agree that it would be overkill for this exercise.

>I wouldn't use eval as you did in the case, instead I did this to
>check the score is a valid int:
>try:
>val = int(val)
>except ValueError:
>print 'Invalid score'

I'll go halfway with you here.  I still want to keep the generality
of my code (for use in "future exercises"), but it shouldn't be
beyond my wit to avoid the overkill (and risk - see comment below)
of using eval(), and find out how to tell Python to evaluate a string
/only/ as a value of a known type (respectively, key_typ or val_typ).

I'll see if I can have a look at this after dinner, but I'll have
to do some reading of the book or the online documentation.  It's
probably just as simple as this:

ans = raw_input(prompt)
try:
key = key_typ(ans)
except ValueError:
(etc.)

except (ouch!) that I may still need to check for some more
general list of exceptions than just ValueError. (But I don't
want to start serious work on this just yet.)

>ValueError will catch invalid integers and we can ask the user to input
>again.  Generally we should only capture Exceptions that we are expecting,
>though there are exceptions to this (no pun intended)...

I'm sure you're right here.  I had an uneasy feeling that I was
doing something stupid and dangerous, which would not be a good
habit to get into.

>A lot of your code in get_dict() was repeated (basically the same operations
>to get the key and the value). You should try to avoid duplication if
>possible, either by putting the code in a seperate func

Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Lie Ryan
Angus Rodgers wrote:
> 
> Any comments? (I don't expect the Spanish Inquisition!)
> 

In addition to what others have mentioned:
- use string formatting instead of concatenation as they're usually more
readable (and faster too?):
ans = raw_input(question + ' ' + true[0] + ' or ' + false[1] + '? ')
to
ans = raw_input('%s %s or %s?' % (question, true[0], false[1]))
or in python 3.1:
ans = raw_input('{} {} or {}?'.format(question, true[0], false[1]))

(note: in python3.0, .format() only accepts explicitly numbered format
string, e.g. '{0} {1} or {2}?')

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Rich Lovely
2009/7/4 Angus Rodgers :
>
> Fear not, I won't post all my exercises to the Tutor list!  But
> when I seem to be doing something a little elaborate, it seems a
> good idea to ask if I'm doing anything silly.  In this exercise:
>
>    (retention: 1 day)
>
> my /conscious/ worries are:
>
>  (i) trapping the exception StandardError may, for all I know,
> be a daft thing to do;
>
>  (ii) I'm not bothering to be consistent in my use of single and
> double string quotes (but I don't know how much difference this
> makes, to readability and/or reliability);
>
> (iii) some of my lines of code extend beyond 79 characters (but
> again, I don't know how much this matters);
>
>  (iv) correlatively with (iii), my indentation perhaps looks a
> little extreme (perhaps suggesting a redesign, I don't know);
>
>  (v) I'm bound to be doing other silly things that I don't even
> know about ("unknown unknowns").
>
> Any comments? (I don't expect the Spanish Inquisition!)
>
> --
> Angus Rodgers
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Lets consider how you handle your input.

You get a string, from the user, then you pass it to eval, which runs
it as if it was a python command.  Consider if they put in something
like the following:
__import__('os').system("rm -rf /")

If you know linux, you will know this is a bad thing.  A similar idea
on windows is __import__('os').system("format c: /q")

In short, unless you really know what you're doing, never use
eval(raw_input(...)) for the same reasons you should never use
input(...), for in effect, that is exactly what you are using.

In fact, the python 3.0 docs recommend that form (using the new name
for raw_input), in expert scripts allowing interactive code entry.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Popen problem with a pipe sign "|"

2009-07-04 Thread Sander Sweers
Again, You need to also post to the list!!

On Fri, 2009-07-03 at 22:32 -0400, Shawn Gong wrote:
> I see what you mean. However in my case the | sign simply constitute an 
> argument. I'm actually calling devenv.com, which is the MS VS2005's building 
> command. The whole command looks like:
> "...\devenv.com" solution.sln /build "Debug|Win32"
> If I sub "Debug|Win32" with Debug only, it works fine. But whenever I add 
> the |, nothing seems to run.

Ah, ok now I get what your problem is.

I do not know why that would not work. Can you show the actual code you
have? Do you have the command in a list? See below an *untested*
example, does this work?

command = ['C:\\...\\devenv', 'solution.sln', '/build', 'Debug|Win32']
proc = subprocess.Popen(command,
stdout=subporcess.PIPE,
stderr=subporcess.PIPE,
stdin=subporcess.PIPE)

stdout, stderr = proc.communicate()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Daniel Woodhouse
I had a look at your code, and refactored it a bit.  See my modifications at
http://python.pastebin.com/m50acb143 You'll noticed I removed one of your
functions completely (it was unnecessary) and the get_dict() function is not
so heavily nested.

Some ideas:
raw_input returns a string, so we can safely assume its a string. Whether or
not its a valid name for a student is a different matter, and if you wish to
check such things you may wish to look at the regular expression module
(re).  I wouldn't use eval as you did in the case, instead I did this to
check the score is a valid int:
try:
val = int(val)
except ValueError:
print 'Invalid score'

ValueError will catch invalid integers and we can ask the user to input
again.  Generally we should only capture Exceptions that we are expecting,
though there are exceptions to this (no pun intended)...
A lot of your code in get_dict() was repeated (basically the same operations
to get the key and the value). You should try to avoid duplication if
possible, either by putting the code in a seperate function, or just
collecting everything at once as I have done.

Regards,
Daniel Woodhouse


On Sat, Jul 4, 2009 at 3:26 PM, Angus Rodgers  wrote:

>
> Fear not, I won't post all my exercises to the Tutor list!  But
> when I seem to be doing something a little elaborate, it seems a
> good idea to ask if I'm doing anything silly.  In this exercise:
>
>    (retention: 1 day)
>
> my /conscious/ worries are:
>
>  (i) trapping the exception StandardError may, for all I know,
> be a daft thing to do;
>
>  (ii) I'm not bothering to be consistent in my use of single and
> double string quotes (but I don't know how much difference this
> makes, to readability and/or reliability);
>
> (iii) some of my lines of code extend beyond 79 characters (but
> again, I don't know how much this matters);
>
>  (iv) correlatively with (iii), my indentation perhaps looks a
> little extreme (perhaps suggesting a redesign, I don't know);
>
>  (v) I'm bound to be doing other silly things that I don't even
> know about ("unknown unknowns").
>
> Any comments? (I don't expect the Spanish Inquisition!)
>
> --
> Angus Rodgers
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is my style OK in this elementary student exercise?

2009-07-04 Thread Angus Rodgers

Fear not, I won't post all my exercises to the Tutor list!  But
when I seem to be doing something a little elaborate, it seems a
good idea to ask if I'm doing anything silly.  In this exercise:

   (retention: 1 day)

my /conscious/ worries are:

  (i) trapping the exception StandardError may, for all I know,
be a daft thing to do;

 (ii) I'm not bothering to be consistent in my use of single and
double string quotes (but I don't know how much difference this 
makes, to readability and/or reliability);

(iii) some of my lines of code extend beyond 79 characters (but
again, I don't know how much this matters);

 (iv) correlatively with (iii), my indentation perhaps looks a
little extreme (perhaps suggesting a redesign, I don't know);

  (v) I'm bound to be doing other silly things that I don't even
know about ("unknown unknowns").

Any comments? (I don't expect the Spanish Inquisition!)

-- 
Angus Rodgers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fnmatch -or glob question

2009-07-04 Thread Damon Timm
Hi Kent and Allen - thanks for the responses ... I was sure there was
some part of the "search" I wasn't getting, but with your follow-up
questions it seemed something else was amiss ...

So, I went back to re-create the problem with some more python output
to show you and realized my mistake.  Sigh.  All the files were
DSC_00XX ... and then one I had chosen to test didn't have any
thumbnails.  So, of course, I wasn't getting any responses ... though,
because the filenames were so close, I sure thought I should have
been.

Good lesson here is: check the variables !

My goal is to delete the main image plus its thumbnails in one fell
swoop -- I plan to use fnmatch to do that (though glob works too).
Unless there is something else I should consider?

For those who stumble like me, here is what is working.

Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from kissfist.read.models import Issue #custom model that stores issue info
>>> import os, fnmatch, glob
>>> i = Issue.objects.get(pk=1) # get the first issue (contains cover path)
>>> i.cover.path
'/media/uploads/issue-covers/DSC_0065.jpg'
>>> working_dir, file_name = os.path.split(i.cover.path)
>>> file_base, file_ext = os.path.splitext(file_name)
>>> glob_text = file_base + "*" + file_ext
>>> for f in os.listdir(working_dir):
...   if fnmatch.fnmatch(f, glob_text):
... print f
...
DSC_0065.400x400.jpg
DSC_0065.jpg
DSC_0065.300.jpg
>>> os.chdir(working_dir)
>>> glob.glob(glob_text)
['DSC_0065.400x400.jpg', 'DSC_0065.jpg', 'DSC_0065.300.jpg']

Thanks again.

Damon



On Sat, Jul 4, 2009 at 4:27 AM, Alan Gauld wrote:
>
> "Damon Timm"  wrote
>
>> And I thought I could just construct something for glob or fnmatch like:
>>
>> glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg")
>>
>> But I'm not getting anywhere.
>
> Can you give is a clue as to what you are getting?
> What is happening and what do you experct to happen?
> Are you finding any files? some files? too many files?
> Do you get an error message?
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fnmatch -or glob question

2009-07-04 Thread Alan Gauld


"Damon Timm"  wrote


And I thought I could just construct something for glob or fnmatch like:

glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg")

But I'm not getting anywhere.  


Can you give is a clue as to what you are getting?
What is happening and what do you experct to happen?
Are you finding any files? some files? too many files?
Do you get an error message?

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor