Re: [Tutor] (no subject)

2010-10-30 Thread Dave Angel

On 2:59 PM, Alan Gauld wrote:


"Steven D'Aprano"  wrote

is actually being executed. There are very few programming tasks 
harder than trying to debug code that doesn't actually contain any 
bugs, or contains bugs different from the ones you are seeing, 
because the code you are actually executing is something different 
from what you think you are executing.


To illustrate with a true story (back in the days when you had to build
and maintain your own compilers!):

Take a C compiler source code and modify it so it produces faulty
executable code but does not crash or otherwise report an error.
Compile the now faulty compiler source code with the old (ie working)
compiler.
Fix the source code bug.
Use the new (now broken) compiler to compile the now perfect source
code to produce a broken compiler with a slightly different defect.
Now use the resulting compiler to recompile the 'perfect' source code.
Now figure out why none of your executables work as expected.

That took us nearly 2 weeks to figure out... :-(
(And made us very thankful for source code version control!)

Alan G.


That sounds remarkably parallel to a speech given by Ken Thompson:
   http://cm.bell-labs.com/who/ken/trust.html

though there the point was that a trojan could be inserted into a 
compiler (or other programming tool) that would survive repair of the 
source code.  There has been at least one viruse which has been credited 
to this approach.


   http://www.symantec.com/connect/blogs/interesting-case-induc-virus


DaveA

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


[Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
FYI: I am working in a linux environment with python 2.6.5
am an experienced web developer with 8 years in python, but
:) I have never tried this trick before:

I note that with the right .htaccess file, I can run a php file,
from a non-cgi location.
Example: On my machine, my wwwroot is at /home/http/, I have
/home/http/php/test/index.php and I have run index.php as
http://localhost/php/test/ (again with the correct .hataccess).

Is it possible to run a python script this way?

thanks
tj
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Evert Rol
> FYI: I am working in a linux environment with python 2.6.5
> am an experienced web developer with 8 years in python, but
> :) I have never tried this trick before:
> 
> I note that with the right .htaccess file, I can run a php file,
> from a non-cgi location.
> Example: On my machine, my wwwroot is at /home/http/, I have
> /home/http/php/test/index.php and I have run index.php as
> http://localhost/php/test/ (again with the correct .hataccess).
> 
> Is it possible to run a python script this way?

I wouldn't think so, because index.php is not run as a cgi-script. 
Whether Python will be interpreted correctly depends entirely on the 
configuration of your webserver, in particular whether you're using/loading the 
correct modules.
But if configured correctly, yes, you can 'run' Python scripts. Mod_wsgi 
arranges this for you, and this is generally how things like Django run.

But the easiest way to find out is to try it out, right?

I also guess this question might be better answered on the forum corresponding 
to your webserver (Apache?), since it appears to deal more with the server 
setup than actually with Python.

Those are my best guesses/ideas.

HTH,

  Evert

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


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread शंतनू
Hi Tim,
Reply inline.

On 31-Oct-2010, at 1:02 AM, Tim Johnson wrote:

> FYI: I am working in a linux environment with python 2.6.5
> am an experienced web developer with 8 years in python, but
> :) I have never tried this trick before:
> 
> I note that with the right .htaccess file, I can run a php file,
> from a non-cgi location.
> Example: On my machine, my wwwroot is at /home/http/, I have
> /home/http/php/test/index.php and I have run index.php as
> http://localhost/php/test/ (again with the correct .hataccess).
> 
> Is it possible to run a python script this way?

Have not tried it, but should be possible. 

Following link could be helpful.
http://docs.python.org/library/cgi.html

>From http://en.wikipedia.org/wiki/Common_Gateway_Interface

===
>From the Web server's point of view, certain locators, e.g. 
>http://www.example.com/wiki.cgi, are defined as corresponding to a program to 
>execute via CGI. When a request for the URL is received, the corresponding 
>program is executed.

Web servers often have a cgi-bin/ directory at the base of their directory tree 
to hold executable files called with CGI.
===

HTH.

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


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* Evert Rol  [101030 13:23]:
> > FYI: I am working in a linux environment with python 2.6.5
> > am an experienced web developer with 8 years in python, but
> > :) I have never tried this trick before:
> > 
> > I note that with the right .htaccess file, I can run a php file,
> > from a non-cgi location.
> > Example: On my machine, my wwwroot is at /home/http/, I have
> > /home/http/php/test/index.php and I have run index.php as
> > http://localhost/php/test/ (again with the correct .hataccess).
> > 
> > Is it possible to run a python script this way?
> 
> I wouldn't think so, because index.php is not run as a cgi-script. 
> Whether Python will be interpreted correctly depends entirely on the 
> configuration of your webserver, in particular whether you're using/loading 
> the correct modules.
> But if configured correctly, yes, you can 'run' Python scripts. Mod_wsgi 
> arranges this for you, and this is generally how things like Django run.
 That's the keyword - 'mod_wsgi' 
> But the easiest way to find out is to try it out, right?
 I did, didn't work.  

> I also guess this question might be better answered on the forum
> corresponding to your webserver (Apache?), since it appears to
> deal more with the server setup than actually with Python.
  Understood. Thanks 

-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2010-10-30 Thread Jacob Bender
Dear Tutors,

 I was wondering how I could make an AI for creatures that run
around, and try to survive. Like polyworld. The real problem is making
the code connection to make them learn. Can you please help?

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


Re: [Tutor] (no subject)

2010-10-30 Thread Tino Dai
On Sat, Oct 30, 2010 at 6:44 PM, Jacob Bender wrote:

> Dear Tutors,
>
> I was wondering how I could make an AI for creatures that run
> around, and try to survive. Like polyworld. The real problem is making
> the code connection to make them learn. Can you please help?
>
> Thanks
>

Hi Jacob,

 That is a really general question. Usually people have a specific
question and/or some code
they are having problems with. I don't know your level of Python knowledge,
but you should check
out http://wiki.hacdc.org/index.php/NARG for more information. They are
doing stuff along the
lines of what you are asking for.

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


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* शंतनू  [101030 14:08]:
> Hi Tim, Reply inline.
 Sorry, I don't understand the preceding line. 
> On 31-Oct-2010, at 1:02 AM, Tim Johnson wrote:
> 
> > FYI: I am working in a linux environment with python 2.6.5 am an
> > experienced web developer with 8 years in python, but :) I have
> > never tried this trick before:
> > 
> > I note that with the right .htaccess file, I can run a php file,
> > from a non-cgi location.  Example: On my machine, my wwwroot is
> > at /home/http/, I have /home/http/php/test/index.php and I have
> > run index.php as http://localhost/php/test/ (again with the
> > correct .hataccess).
> > 
> > Is it possible to run a python script this way?
> 
> 
> Following link could be helpful.
> http://docs.python.org/library/cgi.html
> 
> From http://en.wikipedia.org/wiki/Common_Gateway_Interface
 
> From the Web server's point of view, certain locators, e.g.
> http://www.example.com/wiki.cgi, are defined as corresponding to a
> program to execute via CGI. When a request for the URL is
> received, the corresponding program is executed.
 
> Web servers often have a cgi-bin/ directory at the base of their
> directory tree to hold executable files called with CGI.

  I am familiar with the cgi interface, I've earned a living as a
  web programmer for 15 years and written several CGI APIs from
  scratch, as well as building my own python API on top of the
  standard python cgi module. However, I was approached by a client
  with a whole lot of python code that has grown like topsy without
  a formal framework like django or a CMS, for that matter. The
  client wanted to convert to what he called "clean URLs" not
  showing a cgi-bin path or a file extension. 

  I was well-advised by the previous respondant to post to an apache
  forum or mailing list and he also made reference to mod_wsgi,
  which likely will eventually be implemented on this project.

  For the time being, I did a little work-around:
  1)In my /etc/apache2/sites-available/default I placed the
  following entry:
  """
   ScriptAlias /reg/ /home/http/py/

AllowOverride all
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all

  """
  Note1: This is ubuntu 10.04, apache2 config directories differen
  with linux distros.  
  Note2: The scriptalias entry is *in addition to* the more
  standardized entry creating a cgi-bin path, which I also have, as
  apache2 supports multiple script aliases.

  2)I placed the following .htaccess file at /home/http/py/
"""
RewriteEngine on
RewriteCond $1 !^(index\.py|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.py/$1 [L,QSA]
"""
Disclaimer: I don't do a lot of apache configs and I don't know
beans about .htaccess protocols (always more to learn).
 - and I placed an executable called dispatch.py in the same directory.
Now I can point my browser at http://localhost/reg/dispatch
-with no cgi-bin and no file extension - and get a response.

 So I now can make my customer happy and hold the fort so to speak
 until I get up to speed on either django or mode_wsgi or both.

 Perhaps this info is of interest to others.
 thanks for the replies.
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* Tim Johnson  [101030 15:24]:
  I've taken this one step further:
.htaccess =>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ ./index.py/$1 [L,QSA]
now I get the response from http://localhost/reg/
cheers
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2010-10-30 Thread leo kirotawa
Jacob,

Look about steering behaviours [1], I believe this what you find.

[1] http://www.red3d.com/cwr/steer/

-- 
Leônidas S. Barbosa (Kirotawa)
[DesenvolvedorWeb/CEFET/RN]
[Ciências da Computação/UFRN]
[pós-graduando em Inteligência Computacional/Processamento Gráfico /UFRN
[Estudante de japonês nível Intermediário I  - Japanese Student]
[Desenvolvedor em python, PyGame]
blog nerd: corecode.wordpress.com/
blog music: essenaomanja.blogspot.com
blog tirinhas: elminiche.wordpress.com/

"Mais sábio é aquele que sabe que não sabe" (Sócrates)

日本語の学生です。
コンピュータサイエンスの学位.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Stumped Again

2010-10-30 Thread Terry Green
Am running this Script and cannot figure out how to close my files,

Keep getting msg: Attribute Error: '_csv.writer' object has no attribute
'close'

Why?

 

import csv

testOutput =
csv.writer(open('c:/users/terry/downloads/tup1012k/tup1012.csv', 'w'),
delimiter=',',

 quotechar='"', quoting=csv.QUOTE_NONNUMERIC)

csvreader =
csv.reader(open("c:/users/terry/downloads/tup1012k/tup1012x.drf","r"),delimi
ter=',')

for row in csvreader:

test=('test4')

track=row[0]

rdate=row[1]

race=row[2]

postPos=row[3]

entry=row[4]

distance=row[5]

surface=row[6]

Reserved=row[7]

raceType=row[8]

ageSex=row[9]

todaysRaceClassification=row[10]

purse=row[11]

claimingPrice=row[12]

jockey=row[32]

jockeySts = int(row[34])

jockeyWins = int(row[35])

horseName=row[44]

daysSinceLR=row[223]

try:

jockeyPct=round((jockeyWins/jockeySts)*100)

except ZeroDivisionError:

print
(track,race,postPos,horseName,jockey,jockeyWins,jockeySts,0)

else:

print
(track,race,postPos,horseName,jockey,jockeyWins,jockeySts,jockeyPct)

 
testOutput.writerow((track,race,postPos,horseName,jockey,jockeyWins,jockeySt
s,jockeyPct,'\n'))

testOutput.close()

csvreader.close()

 

Please Help!

 

Terry Green

 

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


Re: [Tutor] Stumped Again

2010-10-30 Thread Brian Jones
On Sat, Oct 30, 2010 at 7:12 PM, Terry Green  wrote:

>  *Am running this Script and cannot figure out how to close my files,*
>
> *Keep getting msg: Attribute Error: ‘_csv.writer’ object has no attribute
> ‘close’*
>
> *Why?*
>

Because csv.writer objects don't have a close() method. Files do :)


> testOutput =
> csv.writer(open('c:/users/terry/downloads/tup1012k/tup1012.csv', 'w'),
>

See this line? testOutput is a csv.writer object, which you pass a file to.
How about creating a file handle first, and passing that in, like this:

testOutputFile = open('c:/users/terry/downloads/whatever.csv', 'w')
testOutputCSV = csv.writer(testOutputFile)

testOutputFile.close()

You can also use the 'with' statement:

with open('c:/users/terry/whatever.csv', 'w') as myfile:
testOutputCSV = csv.writer(myfile)


The 'with' statement is used with ContextManager objects, and files
implement the ContextManager protocol which (among other things) means that
the file will be closed in the above snippet without you having to
explicitly call close() on it.

hth.
brian




> delimiter=',',
>
>  quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
>
> csvreader =
> csv.reader(open("c:/users/terry/downloads/tup1012k/tup1012x.drf","r"),delimiter=',')
>
> for row in csvreader:
>
> test=('test4')
>
> track=row[0]
>
> rdate=row[1]
>
> race=row[2]
>
> postPos=row[3]
>
> entry=row[4]
>
> distance=row[5]
>
> surface=row[6]
>
> Reserved=row[7]
>
> raceType=row[8]
>
> ageSex=row[9]
>
> todaysRaceClassification=row[10]
>
> purse=row[11]
>
> claimingPrice=row[12]
>
> jockey=row[32]
>
> jockeySts = int(row[34])
>
> jockeyWins = int(row[35])
>
> horseName=row[44]
>
> daysSinceLR=row[223]
>
> try:
>
> jockeyPct=round((jockeyWins/jockeySts)*100)
>
> except ZeroDivisionError:
>
> print
> (track,race,postPos,horseName,jockey,jockeyWins,jockeySts,0)
>
> else:
>
> print
> (track,race,postPos,horseName,jockey,jockeyWins,jockeySts,jockeyPct)
>
>
> testOutput.writerow((track,race,postPos,horseName,jockey,jockeyWins,jockeySts,jockeyPct,'\n'))
>
> testOutput.close()
>
> csvreader.close()
>
>
>
> Please Help!
>
>
>
> Terry Green
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Brian K. Jones
My Blog  http://www.protocolostomy.com
Follow me  http://twitter.com/bkjones
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File transfer

2010-10-30 Thread Chris King

 Dear Tutors,
How would I send a file from one computer to another. I have 
modules which can send simple objects, such as dictionaries with simple 
objects in it. They can't send files thou. Please help.


Sincerely,
Me
import SocketServer, cPickle

def echo(self): #the default handling function
print 'Recieved %s from %s. Echoing back.' % (self.data, 
self.client_address)
self.send(self.data) #echo
print self.server

class BreakOutError(Exception): pass #an error for breaking out

def create_handler(handle_func=echo): #creates an handler

class Handler(SocketServer.BaseRequestHandler): #the handler
'''A handler which calls %s in the handle method.'''%handle_func
def handle(self): #the handle method
self.data = self.request.recv(1024) #the data
handle_func(self) #call the handle method giving self

def send(self, data): self.request.send(data) #send data
def shut_down(self): #if you want to stop server
'''End server loop'''
self.server.shut_self_down = True #set shut down to true
raise BreakOutError #raise error

return Handler
def pickle_echo(self):
print 'Recived %s, a %s, from %s. Echoing back.' % (self.data, 
type(self.data), self.client_address)
self.send(self.data)

def pickle_HC(handle_func = pickle_echo): #a function that returns a handler 
that can send a recvieve more than strings if to a pickle client
base = create_handler(handle_func) #make a base
class pickle_Handler(base):
'''A handler which call %s in the handle method and pickle/unpickles on 
the way in and out.'''%handle_func
def handle(self):
self.data = cPickle.loads(self.request.recv(1024)) #unpickle data
handle_func(self)
def send(self, data): base.send(self, cPickle.dumps(data))
return pickle_Handler
class EB_Server(SocketServer.TCPServer):
'''Error Breakout Server
When you use server.shutdown, it waits for the handle to end, but this is the 
only place to do stuff.
So the error breakout server uses error to break out of a server loop, which 
will be caught outside.'''

def __init__(self, address, handler):
'''Init, set self.shutdown to False'''
SocketServer.TCPServer.__init__(self, address, handler) #make a handler 
from a function
self.shut_self_down = False #When an error is raised and handle_error 
catches it, it will check if its an breakout error

def handle_error(self, request, address):
'''Test to see if shutting down.'''
if self.shut_self_down: raise BreakOutError #if shutdown, raise 
breakout error
else: SocketServer.TCPServer.handle_error(self, request, address) #If 
not, do normal error handling

def run(handle_func = echo, host='localhost', port=1024): #init function
try: EB_Server((host, port), create_handler(handle_func)).serve_forever() 
#serve forever
except BreakOutError: pass #If it tries to break out, catch it before it 
destroys us at the main level

def pickle_run(handle_func = pickle_echo, host='localhost', port = 1024):
try: EB_Server((host, port), pickle_HC(handle_func)).serve_forever()
except BreakOutError: pass

if __name__ == '__main__': run() #if run directly, run server
import socket, cPickle

class NotConnectedError(Exception): pass #A ClosedError

class Client(object): #client object

def __init__(self, host = 'localhost', port = 1024, timeout = None):
self.host = host #set attributes
self.port = port
self.timeout = timeout
self.closed = False

def send(self, data): #send data
try: self.__sock.close() #close old socket
except AttributeError: pass #If there isn't a socket, don't worry about 
it
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #make a 
new one
self.__sock.connect((self.host, self.port))
self.closed = False
self.__sock.settimeout(self.timeout)
self.__sock.send(data)

def recv(self): #receive data
if self.closed: raise NotConnectedError, 'The socket isn\'t connected.' 
#if closed, raise error
return self.__sock.recv(1024)

def close(self): #close sock
self.__sock.close()
self.closed = True

def connect(self, host, port): #connect or reconnect
self.__sock.connect((host, port))
self.closed = True #set closed to false

def __get_timeout(self):
try: return self.__sock.gettimeout()
except AttributeError: return self.__timeout #sock may not exist, so do 
predefined

def __set_timeout(self, timeout):
self.__timeout = timeout
try: self.__sock.settimeout(self.__timeout)
except AttributeError: pass #sock may not exist

timeout = property(__get_timeout, __set_timeout)

class Pickle_Client(Client): #a client to send objects, not

Re: [Tutor] Stumped Again

2010-10-30 Thread Steven D'Aprano

Terry Green wrote:

Am running this Script and cannot figure out how to close my files,

Keep getting msg: Attribute Error: '_csv.writer' object has no attribute
'close'

Why?


Lesson one: we're not mind readers. To be able to give you useful 
advise, we need to see the ACTUAL error and not a summary taken out of 
context. Otherwise we're left with making sarcastic replies like 
"because it doesn't have an attribute called 'close'", which makes us 
feel good but doesn't help you.


Python prints a traceback showing the exact error, including the full 
traceback of where it happens. Please COPY AND PASTE the FULL traceback. 
Do NOT summarize it, re-type it from memory, describe it in your own 
words, or otherwise change it in any way. The only exception is if the 
traceback is *huge*, you should say so, and only show the last few 
entries. If we need to see the rest, we'll tell you.


Lesson two: we rarely need to, and never want to, see your entire 
script. Best practice is for you to simplify the problem to the smallest 
piece of code that still fails in the same way. This has three advantages:


(1) By working through the problem yourself, 7 out of 10 times you'll 
work out what the problem is yourself. You will have learned a valuable 
problem-solving skill.


(2) By making the problem small, rather than big, you improve the 
chances that others will have the time and motivation to solve it for you.


(3) You make our life easier, which means we will be kindly disposed to 
you and be more likely to help.



In this case, I think I can solve the problem very easily, using the 
interactive interpreter:


>>> import csv
>>> help(csv.writer.close)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'builtin_function_or_method' object has no attribute 'close'


csv.writer doesn't have a close method, just because that's how it is. 
There's nothing to close. What you need to close is the file object you 
pass to the csv.writer.


import csv

fp = open('c:/users/terry/downloads/tup1012k/tup1012.csv', 'w')
output = csv.writer(fp)
# do stuff with output
# ...
# then close the underlying file object, not the writer.
fp.close()


--
Steven

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


Re: [Tutor] File transfer

2010-10-30 Thread Corey Richardson
If you can send a list, have the list [name, data] where name is the 
file name and data is the raw binary of the file, contained in a string.


On 10/30/2010 9:11 PM, Chris King wrote:

 Dear Tutors,
How would I send a file from one computer to another. I have 
modules which can send simple objects, such as dictionaries with 
simple objects in it. They can't send files thou. Please help.


Sincerely,
Me


___
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