Re: [Tutor] The Format Specification Mini-Language of Python 3.1

2010-10-27 Thread Richard D. Moores
On Wed, Oct 27, 2010 at 09:29, Richard D. Moores  wrote:
> 

> In addition, if you are interested in doing some simple web scraping with
> 3.1, highlighted lines 6, 25, 26 in my code show what worked for me with
> what at first was very hard to understand until I found the examples in the
> docs for the use of urllib.request:
> 

Thought I'd report that there is a "HOWTO Fetch Internet Resources
Using The urllib Package" at


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


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

2010-10-27 Thread Alex Hall
Thanks to all for the explanations. I think I understand how this
works, basically. I doubt I will use the concept anytime soon, but I
think I get it enough to follow what is happening in the source code
of the application I am examining.

On 10/27/10, Siren Saren  wrote:
> Alex,
>
> Many people have trouble wrapping their minds around decorators.  I couldn't
> find a decent explanation either until reading an allegedly 'advanced'
> python book (b/c 'advanced' is in the title, I guess).
>
> An easy explanation might be sufficient, if you don't intend to use them
> yourself.  A decorator is a way of changing a function's behavior.  Most of
> the time you see a decorator, the person using it could have merely
> rewritten the function or method itself and given it some additional
> capability or modified it in some way.  But, as you may have noticed,
> programmers prefer to 'abstract' when they can, so they can avoid
> 'duplicating code.'  (These are buzzwords you'll encounter a lot).
>
> Let's say your program needs to set an index in a lot of different
> functions, and let's further imagine that setting an index is either more
> than a line of code or that the index itself may change over the development
> cycle, or that the index will vary according to some simple pattern
> consistently defined in these other functions.
>
> To avoid writing the same code over and over and having the value of index
> set in many different places, the developers chose instead to write the code
> once and refer to it in all the other functions through a decorator, which
> takes all the functions, modifies them so they get the index values they
> need, and sets them back in their places (more or less).
>
> If you want the more complicated answer, I think I can take a reasonable
> shot at showing how this works too and making an example.  But you may just
> want a general description.  Also, I'm only about 4 months into learning to
> program so you may prefer a more expert opinion.
>
> Cheers,
>
> Soren
>
> --- On Tue, 10/26/10, Alex Hall  wrote:
>
> From: Alex Hall 
> Subject: [Tutor] decorators (the "at" sign)?
> To: "tutor" 
> Date: Tuesday, October 26, 2010, 2:46 AM
>
> Hi all,
> Now that I am able to run the source code of an open source
> application I hope to one day help develop, I am trying to understand
> how it works. One thing I keep seeing is an at sign followed by a
> word, usually (maybe always) immediately preceeding a function
> definition. For example, and I know this exact code will not make much
> sense, but it gives the idea:
> class Bing(Messages, Updating, Dismissable):
>
>  @set_index
>  def get_url(self, index=None):
>   return self.storage[index]['Url']
>
> What is the "@set_index" for? Specifically, what is the at sign doing?
> Google was only able to provide me with a very vague idea of what is
> going on, though it seems to crop up a lot in classmethod and
> staticmethod calls (not sure about those either). I read PEP 318, but
> it was not much help since I am coming at this having no idea what I
> am looking at. The PEP did explain why I have never run into this
> before, though - it is apparently specific to Python. I see this sort
> of thing all over this source code so it seems like a good idea to get
> exactly what it is for. TIA!
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.listdir for symbolic links?

2010-10-27 Thread Lie Ryan
On 10/28/10 06:57, Sean Carolan wrote:
> Is there an easy way to find the target of a symbolic link on a Linux
> system with python?  I'm looking for something like the output of the
> bash command: "ls -l"

you're looking for

>>> os.path.realpath('/bin/uncompress')
'/bin/gunzip'

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


[Tutor] os.listdir for symbolic links?

2010-10-27 Thread Sean Carolan
Is there an easy way to find the target of a symbolic link on a Linux
system with python?  I'm looking for something like the output of the
bash command: "ls -l"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python xlwt unicoderror

2010-10-27 Thread Susana Iraiis Delgado Rodriguez
I'm starting to use xlwt to create excel files, my excel sheet is designed
to get information from a python module. The data came from a raster file,
the problem is that some kind of sign or character doesn't allow the file to
be written. This is my script:

import sys, os, time, socket, codecs
from xlwt import Workbook
from osgeo import gdal
from osgeo.gdalconst import *
from PIL import Image

gdal.AllRegister()
file_list = []
folders = None
 # look in this (root) folder for files with specified extension
for root, folders, files in os.walk( "C:\\" ):
 file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(".tif") or fi.endswith(".tiff") or fi.endswith(".gtif") or
fi.endswith(".ecw") or fi.endswith(".bil") or fi.endswith(".til") or
fi.endswith(".jpeg") or fi.endswith(".img") or fi.endswith(".jpg"))
wrkbk = Workbook()
 #Add named parameter to allow overwriting cells: cell_overwrite_ok=True
wksht = wrkbk.add_sheet('raster')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'nombre')
wksht.row(0).write(2,'x_min')
wksht.row(0).write(3,'x_max')
wksht.row(0).write(4,'y_min')
wksht.row(0).write(5,'y_max')
wksht.row(0).write(6,'ancho_pixel')
wksht.row(0).write(7,'alto_pixel')
wksht.row(0).write(8,'num_filas')
wksht.row(0).write(9,'num_columnas')
wksht.row(0).write(10,'num_bandas')
wksht.row(0).write(11,'proyeccion')
wksht.row(0).write(12,'fecha_modificacion')
wksht.row(0).write(13,'maquina_host')
wksht.row(0).write(14,'usuario')

for row, filepath in enumerate(file_list, start=1):
 #Llenar lista de archivos y ruta
 unicode(filepath, errors='ignore')
 wksht.row(row).write(0, filepath)
 #Escribir solo el nombre del archivo
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 unicode(filename, errors='ignore')
 # Obtener coordenadas x/y
 dataset = gdal.Open(filepath, GA_ReadOnly)
 if dataset is None:
  print 'Could not open...' +filename

 #iNFORMACIoN GEOREFERENCIA
 else:
  xOrigin, yOrigin, pixelWidth, pixelHeight, a, b =
dataset.GetGeoTransform()
  geotransform = dataset.GetGeoTransform(

 #Obtener coordenadas
  x_min = geotransform[0]
  wksht.row(row).write(2,x_min)
  y_max = geotransform[3]
  wksht.row(row).write(5,y_max)
  pixel_width = geotransform[1]
  wksht.row(row).write(6,pixel_width)
  pixel_height = geotransform[5]
  wksht.row(row).write(7,pixel_height)

 #Obtener tamano de la imagen
  rows = dataset.RasterYSize
  cols = dataset.RasterXSize
  bands = dataset.RasterCount

  wksht.row(row).write(8,rows)
  wksht.row(row).write(9,cols)
  wksht.row(row).write(10,bands)

  x_max= (pixel_width - x_min) / pixel_width
  y_min = (y_max - x_min) / pixel_height
  wksht.row(row).write(3,x_max)
  wksht.row(row).write(4,y_min)


 #Obtener la proyeccion
  n = os.path.splitext(filepath)
  tif = n[0]+'.tif'
  tiff = n[0]+'.tiff'
  gtif = n[0]+'.gtif'
  ecw = n[0]+'.ecw'
  bil = n[0]+'.bil'
  til = n[0]+'.til'
  img = n[0]+'.img'
  jpg = n[0]+'.jpg'
  jpeg = n[0]+'.jpeg'
  if os.path.lexists(tif) or os.path.lexists(tiff) or os.path.lexists(gtif)
or os.path.lexists(ecw) or os.path.lexists(bil) or os.path.lexists(til) or
os.path.lexists(jpg) or os.path.lexists(jpeg):
   wksht.row(row).write(11, dataset.GetProjection())
   #print filename
  else:
   wksht.row(row).write(11, "No tiene proyeccion")

 #Obtner el nombre del host del archivo
  wksht.row(row).write(13, socket.gethostname())

 #Obtener usuario
  wksht.row(row).write(14,os.environ.get("USERNAME"))

 #Obtener fecha de modificacion
   t = time.strftime("%m/%d/%Y %I:%M:%S
%p",time.localtime(os.path.getmtime(filepath)))
  wksht.row(row).write(15, t)

codecs.EncodedFile(wrkbk, "UTF8",errors='ignore')
wrkbk.save('rasters.xls')

SEARCH_PATH = os.getcwd()
TARGET_FILE = os.path.realpath('shp.xls')
print "Buscando en", SEARCH_PATH, "and writing to", TARGET_FILE
print "Encontrando archivos..."
print "Escribiendo archivo de Excel..."
print "Listo."
The error is:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import crawler_img
ERROR 4: `C:\Archivos de programa\WinAce\menuimg.img' not recognised as a
suppor
ted file format.
Could not open...menuimg.img
ERROR 4: `C:\Archivos de programa\WinAce\toolimg.img' not recognised as a
suppor
ted file format.
Could not open...toolimg.img
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[6].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[6].jpg
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[7].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[7].jpg
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[8].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[8].jpg
ERROR 4: `C:\Docume

Re: [Tutor] Which string operation is best to extract text from database string?

2010-10-27 Thread Emile van Sebille

On 10/27/2010 9:45 AM Sean Carolan said...

Forgive me for the newbie question; I'm sure there must be an easy way
to do this in python:

I have a database string that I'm grabbing from a file with readlines():

db.url=jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL =
TCP)(HOST = server.company.com)(PORT =1521)) (ADDRESS = (PROTOCOL =
TCP)(HOST = server.company.com)(PORT = 1521)) (ADDRESS = (PROTOCOL
=TCP)(HOST = server.company.com)(PORT = 1521)) (LOAD_BALANCE = ON)
(FAILOVER = ON) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME =
PROD2) (FAILOVER_MODE = (TYPE = SELECT) (METHOD = BASIC) (RETRIES =
180) (DELAY = 5

I want to extract the service name, PROD2 from the string.  Normally
I'd do this with sed or awk, but I'm trying to get away from using
OS-dependent tools with Popen, etc.  What would be the most efficient
way to grab "PROD2" from this string of text?



Assuming you've got that string in variable text, and that "SERVICE_NAME 
=" is there to be found, I'd do something like


servicename = text.split("SERVICE_NAME =")[1].split(")")[0]

Emile

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


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

2010-10-27 Thread Dave Angel



On 2:59 PM, Roy Hinkelman wrote:

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

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

Now, this is very strange.

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

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

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

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

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

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

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

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

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

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

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

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

 _soup = B_S(html)

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

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

 return _thumb

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

Roy Hinkelman


I don't know anything about PHP, so take the following for what it's worth.

So where is mechanize.py ?  The import error means that it can't be 
found.  Yet if you run the program standalone it's finding it?  My guess 
is that it depends on the current directory when you enter the script.


First thing to do is to split the import line, so that the import 
mechanize follows the others on its own line.  Then you can put some 
debugging lines in between them, perhaps saving off the os.curdir and 
sys.path values.  I suspect the difference between running under php and 
from command line is in one of those.


DaveA



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


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

2010-10-27 Thread Siren Saren
Alex,

Many people have trouble wrapping their minds around decorators.  I couldn't 
find a decent explanation either until reading an allegedly 'advanced' python 
book (b/c 'advanced' is in the title, I guess).

An easy explanation might be sufficient, if you don't intend to use them 
yourself.  A decorator is a way of changing a function's behavior.  Most of the 
time you see a decorator, the person using it could have merely rewritten the 
function or method itself and given it some additional capability or modified 
it in some way.  But, as you may have noticed, programmers prefer to 'abstract' 
when they can, so they can avoid 'duplicating code.'  (These are buzzwords 
you'll encounter a lot).

Let's say your program needs to set an index in a lot of different functions, 
and let's further imagine that setting an index is either more than a line of 
code or that the index itself may change over the development cycle, or that 
the index will vary according to some simple pattern consistently defined in 
these other functions.

To avoid writing the same code over and over and having the value of index set 
in many different places, the developers chose instead to write the code once 
and refer to it in all the other functions through a decorator, which takes all 
the functions, modifies them so they get the index values they need, and sets 
them back in their places (more or less).

If you want the more complicated answer, I think I can take a reasonable shot 
at showing how this works too and making an example.  But you may just want a 
general description.  Also, I'm only about 4 months into learning to program so 
you may prefer a more expert opinion.  

Cheers,

Soren

--- On Tue, 10/26/10, Alex Hall  wrote:

From: Alex Hall 
Subject: [Tutor] decorators (the "at" sign)?
To: "tutor" 
Date: Tuesday, October 26, 2010, 2:46 AM

Hi all,
Now that I am able to run the source code of an open source
application I hope to one day help develop, I am trying to understand
how it works. One thing I keep seeing is an at sign followed by a
word, usually (maybe always) immediately preceeding a function
definition. For example, and I know this exact code will not make much
sense, but it gives the idea:
class Bing(Messages, Updating, Dismissable):

 @set_index
 def get_url(self, index=None):
  return self.storage[index]['Url']

What is the "@set_index" for? Specifically, what is the at sign doing?
Google was only able to provide me with a very vague idea of what is
going on, though it seems to crop up a lot in classmethod and
staticmethod calls (not sure about those either). I read PEP 318, but
it was not much help since I am coming at this having no idea what I
am looking at. The PEP did explain why I have never run into this
before, though - it is apparently specific to Python. I see this sort
of thing all over this source code so it seems like a good idea to get
exactly what it is for. TIA!


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
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