[Tutor] apihelper in dive into python

2014-03-19 Thread Robert.Gutmann
Hi guys,

I've got the following problem: I tried to run the example-program apihelper.py 
in chapter IV of Dive into Python and got the following error message:

Define the builtin 'help'.
This is a wrapper around pydoc.help (with a twist).

This is not the Output I expected, however I have no idea how to fix this.
Anyone an idea?

I am running a Win7 and Python(x,y) 2.7.5.1

Thanks for your help!
Robert
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loop through hours to calc max and plot

2014-03-19 Thread Alan Gauld

On 19/03/14 05:12, questions anon wrote:


I have monthly netcdf files containing hourly temperature data.
I would like to loop through all of the hours and calculate the max for
each hour (00 - 23) and then make a plot.


Its hard to give specific help since I don't know the file format
and most of your code is using non standard-library modules.

A couple of suggestions would be to
1) convert the code into a few functions each doing one
   specific job. For example the plotting code and the
   reading code could be separated out. That makes it
   easier to read the overall program flow and easier
   to test those individual functions if you change them.
2) You have quite a few redundant or misplaced assignments
   going on, or things happening inside loops that
   shouldn't be. Again removing the surplus just makes
   the rest of the code easier to grasp.


I have found a way for this to work for a couple of the hours (see
below) but it requires a lot of set up to do each hour and I am sure
there must be a simpler way using loops? I also need to find a simpler
way as I would like to eventually do daily for 1st jan to 31st Dec


If you put the code into smaller functions that will simplify the design 
of your bigger program. Each function should have one clear purpose and 
be as standalone as possible. It should take in the

date it needs as parameters and pass back a value.



from netCDF4 import Dataset
import numpy as N
import matplotlib.pyplot as plt
from numpy import ma as ma
from mpl_toolkits.basemap import Basemap
from netcdftime import utime
from datetime import datetime
import os
from matplotlib.collections import LineCollection

shapefile1=---
OutputFolder=r/---/
fileforlatlon=Dataset(---.nc, 'r+', 'NETCDF4')
LAT=fileforlatlon.variables['latitude'][:]
LON=fileforlatlon.variables['longitude'][:]

#Set up basemap using mercator projection



map =
Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
x,y=map(*N.meshgrid(LON,LAT))
map.readshapefile(shapefile1, '-REGIONS')



ncvariablename='T_SFC'
MainFolder=r/---/
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
Title='Surface Temperature (degrees celsius)'


Why aren't these with the other initialization code above?


cmap=plt.cm.jet




all_variabledata=[]
time00=[]
time12=[]


Why aren't these with the other initialization code above?


for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print the dirs are:, dir
path=path+'/'


this appears to be in the loop but its the same
value each time so you repeat the same assignment
over and over.



for ncfile in files:
fileext=ncvariablename+'.nc'
if ncfile.endswith(fileext):
print dealing with ncfiles:, path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
TIME=ncfile.variables['time'][1::]
#variable=ncfile.variables[ncvariablename][:,:,:]
TSFC00=ncfile.variables[ncvariablename][00:01:,:,:]
TSFC12=ncfile.variables[ncvariablename][12:13:,:,:]
fillvalue=ncfile.variables[ncvariablename]._FillValue
ncfile.close()


Indentation seems to have gotten lost in email transit.
Maybe you didn't post in plain text?



#combine all data from the chosen variable to make one array for analyses
cdftime=utime('seconds since 1970-01-01 00:00:00')
ncfiletime=cdftime.num2date(TIME)
for i in ncfiletime[:]:
ncfiletime=i


This is a really bad idea. You are using the same variabvle name to hold 
the collection you iterate over then reassigning it to the items within 
the loop. Why not just use i (but use a better name!) within

the loop body rather than reassign it?

And if you must reassign it use a name other than the one you already 
used for the collection. Using the same name in two different ways

is a recipe for confusion.


timestr=str(ncfiletime)
d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
date_string = d.strftime('%H')#combine by same hour
print the ncfiletime is:, ncfiletime

print the date_string is:, date_string
if date_string=='00':
time00.append(TSFC00)
elif date_string=='12':
time12.append(TSFC12)
else:
pass

big_arraytime00=N.ma.concatenate(time00)
big_arraytime12=N.ma.concatenate(time12)
MAX00=big_arraytime00.max(axis=0)
MAX12=big_arraytime12.max(axis=0)

#plot output summary stats
map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,
llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
map.drawcoastlines()
map.drawstates()
map.readshapefile(shapefile1, 'REGIONS')
x,y=map(*N.meshgrid(LON,LAT))
plottitle='TSFCmax00'


another constant assignment that could be in the
initialization code section


plt.title(plottitle)
CS = map.contourf(x,y,MAX00, ticks, cmap=cmap)



l,b,w,h =0.1,0.1,0.8,0.8
cax = plt.axes([l+w+0.025, b, 0.025, h])
plt.colorbar(CS,cax=cax, drawedges=True)
plt.savefig((os.path.join(OutputFolder, plottitle+'.png')))
plt.show()
plt.close()


map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,
llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
map.drawcoastlines()

Re: [Tutor] apihelper in dive into python

2014-03-19 Thread Peter Otten
robert.gutm...@dlr.de wrote:

 Hi guys,
 
 I've got the following problem: I tried to run the example-program
 apihelper.py in chapter IV of Dive into Python and got the following
 error message:
 
 Define the builtin 'help'.
 This is a wrapper around pydoc.help (with a twist).
 
 This is not the Output I expected, however I have no idea how to fix this.
 Anyone an idea?
 
 I am running a Win7 and Python(x,y) 2.7.5.1
 
 Thanks for your help!
 Robert

Do you mean the apihelper.py module from 

http://www.diveintopython.net/download/diveintopython-examples-5.4.zip

(comments etc. omitted)?

def info(object, spacing=10, collapse=1):
Print methods and doc strings.

Takes module, class, list, dictionary, or string.
methodList = [e for e in dir(object) if callable(getattr(object, 
e))]
processFunc = collapse and (lambda s:  .join(s.split())) or 
(lambda s: s)
print \n.join([%s %s %
 (method.ljust(spacing),
  processFunc(str(getattr(object, 
method).__doc__)))
 for method in methodList])

if __name__ == __main__:
print help.__doc__


When you run that as a script it does not invoke the info() function, it 
just prints help.__doc__ which is what you see. However the code on 

http://www.diveintopython.net/power_of_introspection/

differs from the above as it prints info.__doc__ instead of help.__doc__. If 
that's what you expected just change the last line in apihelper.py from

print help.__doc__

to

print info.__doc__

With this change the script will print the docstring of the info() function:

$ python apihelper.py
Print methods and doc strings.

Takes module, class, list, dictionary, or string.


But what apihelper is really meant for is interactive interpreter sessions:

 import apihelper
 apihelper.info(42)
__abs__x.__abs__() == abs(x)
__add__x.__add__(y) == x+y
__and__x.__and__(y) == xy
[snip a lot more methods]

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


[Tutor] How to create a sqlite table schema dynamically

2014-03-19 Thread Toni Fuente
Hello everyone,

I am stack with a problem that I can't find a solution:

I need to create a sqlite schema dynamically, I've got a dictionary with
text keys: RedHat, CentOS, SLES9,..., etc, etc

My intention was at the time of creating the table schema run a loop
through the dictionary keys and incorporate them to the schema:

for os in osDict.items():
   cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, 
number INTEGER NOT NULL)''')

But I don't know how to pass the os key to the sqlite command.

Thank you in advance for any help,
Kind regards,


-- 
Toni

Tímido Busca..., Bueno No..., Es Igual... Nada.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How to get file permissions (Python 2.4)?

2014-03-19 Thread leam hall
I can use os.chmod('/usr/local/somefile') to change permissions but I
haven't been able to find a way to test for file modes.

 stat.S_IRWXU('/usr/bin/python')
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: 'int' object is not callable

What should I be looking for? Python 2.4.3 (RHEL 5)

Thanks!

Leam

-- 
Mind on a Mission
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get file permissions (Python 2.4)?

2014-03-19 Thread Martin A. Brown

Hi there,

 : I can use os.chmod('/usr/local/somefile') to change permissions 
 : but I haven't been able to find a way to test for file modes.
 : 
 :  stat.S_IRWXU('/usr/bin/python')
 : Traceback (most recent call last):
 :   File stdin, line 1, in ?
 : TypeError: 'int' object is not callable
 : 
 : What should I be looking for? Python 2.4.3 (RHEL 5)

You are using the stat module [0].  You need to get the stat info 
separately.  Here's the first paragraph from the stat module docs:

  The stat module defines constants and functions for interpreting 
  the results of os.stat(), os.fstat() and os.lstat() (if they 
  exist). For complete details about the stat(), fstat() and 
  lstat() calls, consult the documentation for your system.

This looks a bit ugly and error-prone to me, but you could do 
something like this:

  stat.S_IRWXU  os.stat('/usr/bin/python').st_mode

Better yet?  Let os.access() [1] do the bitmath for you:

  os.access('/usr/bin/python', os.X_OK)

Good luck,

-Martin

 [0] http://docs.python.org/2/library/stat.html
 [1] http://docs.python.org/2/library/os.html#os.access

-- 
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get file permissions (Python 2.4)?

2014-03-19 Thread Walter Prins
Hi

On 19 March 2014 18:48, leam hall leamh...@gmail.com wrote:
 I can use os.chmod('/usr/local/somefile') to change permissions but I
 haven't been able to find a way to test for file modes.

 stat.S_IRWXU('/usr/bin/python')
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: 'int' object is not callable

 What should I be looking for? Python 2.4.3 (RHEL 5)

You're using the stat module as described here:
http://docs.python.org/2/library/stat.html

The constant stat.S_IRWXU is listed under a section that just to
defining the constant, reads:

The following flags can also be used in the mode argument of os.chmod():

Which means, that you can do, for something like:

 import os
 import stat
 os.chmod('/some/file/some/where', stat.S_IRWXU)

This has the effect of changing the file mode for the specified file
to read, write, execute for the user only and is the equivalent of
executing 'chmod u+rwx /some/file' or 'chmod 700 /some/file' from the
command line.

HTH,

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


[Tutor] mixing 64 bit and 32 bit

2014-03-19 Thread John Fabiani

Hi,

At my office we have a mix of XP (32bit) and Window 7 (64 bit).  I 
installed python 64 bit on the windows 7 machines and 32 bit on the XP 
machines.  The question is can the different version run the same code 
without causing issues.  Can the 64 bit use the same byte code as the 32 
bit?  It seems to be working but I thought best to check.


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


Re: [Tutor] mixing 64 bit and 32 bit

2014-03-19 Thread Reuben
Hi John,

The generated bytecodes will be different - but both version can run same
code without issues

Regards,
Reuben
On 19-Mar-2014 11:28 PM, John Fabiani jo...@jfcomputer.com wrote:

 Hi,

 At my office we have a mix of XP (32bit) and Window 7 (64 bit).  I
 installed python 64 bit on the windows 7 machines and 32 bit on the XP
 machines.  The question is can the different version run the same code
 without causing issues.  Can the 64 bit use the same byte code as the 32
 bit?  It seems to be working but I thought best to check.

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

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


Re: [Tutor] How to create a sqlite table schema dynamically

2014-03-19 Thread Mark Lawrence

On 19/03/2014 12:19, Toni Fuente wrote:

Hello everyone,

I am stack with a problem that I can't find a solution:

I need to create a sqlite schema dynamically, I've got a dictionary with
text keys: RedHat, CentOS, SLES9,..., etc, etc

My intention was at the time of creating the table schema run a loop
through the dictionary keys and incorporate them to the schema:

for os in osDict.items():
cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT 
NULL, number INTEGER NOT NULL)''')

But I don't know how to pass the os key to the sqlite command.

Thank you in advance for any help,
Kind regards,




http://docs.python.org/3/library/sqlite3.html#module-sqlite3 the 7th 
paragraph describes 'parameter substitution'


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] mixing 64 bit and 32 bit

2014-03-19 Thread John Fabiani

Thanks
Johnf
On 03/19/2014 11:01 AM, Reuben wrote:


Hi John,

The generated bytecodes will be different - but both version can run 
same code without issues


Regards,
Reuben

On 19-Mar-2014 11:28 PM, John Fabiani jo...@jfcomputer.com 
mailto:jo...@jfcomputer.com wrote:


Hi,

At my office we have a mix of XP (32bit) and Window 7 (64 bit).  I
installed python 64 bit on the windows 7 machines and 32 bit on
the XP machines.  The question is can the different version run
the same code without causing issues.  Can the 64 bit use the same
byte code as the 32 bit?  It seems to be working but I thought
best to check.

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



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


[Tutor] is set/getlocale buggy in OS X?

2014-03-19 Thread Albert-Jan Roskam


I got several unexpected results using locale.getlocale under OS X. On one 
computer (not mine) it returned (None, None), even though I used setlocale. Now 
I am getting the result below on my own computer. Is there a good workaround 
for this? 

Albert-Jans-Mac-Pro:macos albertjan$ uname -a
Darwin Albert-Jans-Mac-Pro.local 12.2.0 Darwin Kernel Version 12.2.0: Sat Aug 
25 00:48:52 PDT 2012; root:xnu-2050.18.24~1/RELEASE_X86_64 x86_64

Albert-Jans-Mac-Pro:macos albertjan$ python

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type help, copyright, credits or license for more information.
 import locale
 locale.setlocale(locale.LC_ALL, )
'C/UTF-8/C/C/C/C'
 locale.getlocale()
Traceback (most recent call last):
  File stdin, line 1, in module
  File 
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py,
 line 515, in getlocale
    return _parse_localename(localename)
  File 
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py,
 line 428, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8 



Thank you!


Regards,

Albert-Jan




~~

All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

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


[Tutor] FW: Beginner - list not returning correct variable value

2014-03-19 Thread Marc Eymard
Hello Tutor,

Could somebody help me with below query?

Thanks
Marc

From: marc_eym...@hotmail.com
To: tutor@python.org
Subject: Beginner - list not returning correct variable value
Date: Thu, 13 Mar 2014 16:12:28 +




Hello Tutor,

I am a self-taught Python script beginner and I do it from the Michael Dawson 
Book.

In attached script, can somebody tell me why the values of the variables 
strenght_points, health_points, wisdom_points and dexterity_points stay at 0 
value when 'printing' their value from the list attributes[] when the 'for' 
loop at the bottom of the script runs.

I have commented out the script to highlight what causes me problem.

I hope this is clear enough a question.

Thanks for your help,
Marc

  #Character role play
#you have 4 attributes and can assign/remove points to/from it
#use short story scripting to task with no MENU tree
#ignore calculus logic limitations

#set variables
strength_points = 0
health_points = 0
wisdom_points = 0
dexterity_points = 0
pool = 30
att_choice = None

attributes = [('strength',strength_points),
  ('health',health_points),
  ('wisdom',wisdom_points),
  ('dexterity',dexterity_points)]



print('Hello gladiator,\n')

print('you have the following attributes with no points:\n')

for i in attributes:
att_name, points = i
print(att_name,'\t',points)

input('\nPress ENTER to continue')

print('\nYou are now entrusted with a pool of 30 points to spend on them as you whish')
input('Press ENTER to continue')

print('\nUsing negative points will move them back to your pool of points')
input('Press ENTER to continue')

print('\nChose an attribute and add/remove points at your will:   ')

while att_choice != '0':

#here proof that variables values are changing as expexted:
print('here proof that variables values are changing as expected:')
print(strength_points,health_points,wisdom_points,dexterity_points,pool)


print('\n[1] stength [2] health [3] wisdom [4] dexterity [0] EXIT')
att_choice = input('ENTER number here: ')

if att_choice == '1':
  print('\nHow many strenght points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  strength_points += points
  pool -= points

elif att_choice == '2':
  print('\nHow many health points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  health_points += points
  pool -= points

elif att_choice == '3':
  print('\nHow many wisdom points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  wisdom_points += points
  pool -= points

elif att_choice == '4':
  print('\nHow many dexterity points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  dexterity_points += points
  pool -= points

elif att_choice == '0':
print('Good Bye Gladiator!')
break

else:
print('Sorry I don\'t understand your selection')
input('Press ENTER to try again')

print('\nYou have now the following attributes and points:\n')

#here the loop does not return variable value as expected:
for i in attributes:
att_name, point = i
print(att_name,'\t',point)

input('\nPress ENTER to continue\n')

input('\nPress ENTER to exit')


  

  



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


Re: [Tutor] FW: Beginner - list not returning correct variable value

2014-03-19 Thread Danny Yoo
Hmm.  Did you get Alan's reply six days ago?  Here's a link to his
reply, just in case you've missed it:

   https://mail.python.org/pipermail/tutor/2014-March/100580.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Beginner - list not returning correct variable value

2014-03-19 Thread Mark Lawrence

On 19/03/2014 20:41, Marc Eymard wrote:

Hello Tutor,

Could somebody help me with below query?

Thanks
Marc


From: marc_eym...@hotmail.com
To: tutor@python.org
Subject: Beginner - list not returning correct variable value
Date: Thu, 13 Mar 2014 16:12:28 +

Hello Tutor,

I am a self-taught Python script beginner and I do it from the Michael
Dawson Book.

In attached script, can somebody tell me why the values of the variables
strenght_points, health_points, wisdom_points and dexterity_points stay
at 0 value when 'printing' their value from the list attributes[] when
the 'for' loop at the bottom of the script runs.

I have commented out the script to highlight what causes me problem.

I hope this is clear enough a question.

Thanks for your help,
Marc



What was wrong with Alan Gauld's reply that was posted on the same day 
as your original query?


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] How to get file permissions (Python 2.4)?

2014-03-19 Thread Alan Gauld

On 19/03/14 16:48, leam hall wrote:

I can use os.chmod('/usr/local/somefile') to change permissions but I
haven't been able to find a way to test for file modes.


stat.S_IRWXU('/usr/bin/python')

Traceback (most recent call last):
   File stdin, line 1, in ?
TypeError: 'int' object is not callable

What should I be looking for? Python 2.4.3 (RHEL 5)


v2.4? Hmm, old. I think this is still valid tho'

Look in the os.path module for a bunch of mode/access
test functions for common tests.

Or

os.access() takes a filename and flag variable (one of os.F_OK,
os.R_OK, os.W_OK, and os.X_OK) which returns a Boolean result depending 
on whether the file exists, is readable, writable or executable 
respectively.


Alternatively use os.stat() and treat the mode attribute
result as a bitmask using the stat flags

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] loop through hours to calc max and plot

2014-03-19 Thread ALAN GAULD
Forwarding to the list.
Use ReplyAll when responding to ensure maximum responses.
 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/

http://www.flickr.com/photos/alangauldphotos




 From: questions anon questions.a...@gmail.com
To: Alan Gauld alan.ga...@btinternet.com 
Sent: Wednesday, 19 March 2014, 22:30
Subject: Re: [Tutor] loop through hours to calc max and plot
 


Could you please give an example of how to put these into a loop in a function 
and create the matching naming conventions?




On Thu, Mar 20, 2014 at 8:07 AM, questions anon questions.a...@gmail.com 
wrote:

Thank you for your response it is very helpful.





On Wed, Mar 19, 2014 at 8:16 PM, Alan Gauld alan.ga...@btinternet.com wrote:

On 19/03/14 05:12, questions anon wrote:


I have monthly netcdf files containing hourly temperature data.
I would like to loop through all of the hours and calculate the max for
each hour (00 - 23) and then make a plot.


Its hard to give specific help since I don't know the file format
and most of your code is using non standard-library modules.

A couple of suggestions would be to
1) convert the code into a few functions each doing one
   specific job. For example the plotting code and the
   reading code could be separated out. That makes it
   easier to read the overall program flow and easier
   to test those individual functions if you change them.
2) You have quite a few redundant or misplaced assignments
   going on, or things happening inside loops that
   shouldn't be. Again removing the surplus just makes
   the rest of the code easier to grasp.



I have found a way for this to work for a couple of the hours (see
below) but it requires a lot of set up to do each hour and I am sure
there must be a simpler way using loops? I also need to find a simpler
way as I would like to eventually do daily for 1st jan to 31st Dec


If you put the code into smaller functions that will simplify the design of 
your bigger program. Each function should have one clear purpose and be as 
standalone as possible. It should take in the
date it needs as parameters and pass back a value.




from netCDF4 import Dataset
import numpy as N
import matplotlib.pyplot as plt
from numpy import ma as ma
from mpl_toolkits.basemap import Basemap
from netcdftime import utime
from datetime import datetime
import os
from matplotlib.collections import LineCollection

shapefile1=---
OutputFolder=r/---/
fileforlatlon=Dataset(---.nc, 'r+', 'NETCDF4')
LAT=fileforlatlon.variables['latitude'][:]
LON=fileforlatlon.variables['longitude'][:]

#Set up basemap using mercator projection


map =
Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
x,y=map(*N.meshgrid(LON,LAT))
map.readshapefile(shapefile1, '-REGIONS')


ncvariablename='T_SFC'
MainFolder=r/---/
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
Title='Surface Temperature (degrees celsius)'


Why aren't these with the other initialization code above?


cmap=plt.cm.jet



all_variabledata=[]
time00=[]
time12=[]

Why aren't these with the other initialization code above?



for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print the dirs are:, dir
path=path+'/'


this appears to be in the loop but its the same
value each time so you repeat the same assignment
over and over.




for ncfile in files:
fileext=ncvariablename+'.nc'
if ncfile.endswith(fileext):
print dealing with ncfiles:, path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
TIME=ncfile.variables['time'][1::]
#variable=ncfile.variables[ncvariablename][:,:,:]
TSFC00=ncfile.variables[ncvariablename][00:01:,:,:]
TSFC12=ncfile.variables[ncvariablename][12:13:,:,:]
fillvalue=ncfile.variables[ncvariablename]._FillValue
ncfile.close()


Indentation seems to have gotten lost in email transit.
Maybe you didn't post in plain text?




#combine all data from the chosen variable to make one array for analyses
cdftime=utime('seconds since 1970-01-01 00:00:00')
ncfiletime=cdftime.num2date(TIME)
for i in ncfiletime[:]:
ncfiletime=i


This is a really bad idea. You are using the same variabvle name to hold the 
collection you iterate over then reassigning it to the items within the loop. 
Why not just use i (but use a better name!) within
the loop body rather than reassign it?

And if you must reassign it use a name other than the one you already used 
for the collection. Using the same name in two different ways
is a recipe for confusion.



timestr=str(ncfiletime)
d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
date_string = d.strftime('%H')#combine by same hour
print the ncfiletime is:, ncfiletime

print the date_string is:, date_string
if date_string=='00':
time00.append(TSFC00)
elif date_string=='12':
time12.append(TSFC12)
else:
pass

big_arraytime00=N.ma.concatenate(time00)
big_arraytime12=N.ma.concatenate(time12)
MAX00=big_arraytime00.max(axis=0)

Re: [Tutor] How to get file permissions (Python 2.4)?

2014-03-19 Thread Steven D'Aprano
On Thu, Mar 20, 2014 at 01:13:28AM +, Alan Gauld wrote:
 On 19/03/14 16:48, leam hall wrote:
 I can use os.chmod('/usr/local/somefile') to change permissions but I
 haven't been able to find a way to test for file modes.
 
 stat.S_IRWXU('/usr/bin/python')
 Traceback (most recent call last):
File stdin, line 1, in ?
 TypeError: 'int' object is not callable
 
 What should I be looking for? Python 2.4.3 (RHEL 5)
 
 v2.4? Hmm, old. I think this is still valid tho'

2.4 is old, but it's still supported by Red Hat Enterprise Linux, so it 
will be around for a few more years.


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