server question

Peter Hansen peter at engcorp.com
Sat Aug 11 14:46:38 EDT 2001


vin wrote:
[...]
> Now I know that conn.recv() should return a string, but it seems that I
> can't evaluate that string with eval.  You can print 'data' but not do
> eval(data) it always reports syntax error.  Why?

Try printing repr(data) instead of just data and notice what
your data actually contains.  Hint: telnet is probably
adding something that eval() can't handle.  Look into 
using string.strip() on the data, if you really want to do 
this the "hard way" (i.e. building it yourself).
In general, if you are concerned about the *content*
of the data, don't use just 'print' when debugging -- 
use 'print repr()' instead to see all the bytes.

As I mentioned before, however, you have no guarantees 
that recv() returns a single string with all the input.
You need to recv() from the socket repeatedly in a loop,
checking for a termination sequence like '\n', and collect
the input into a buffer for later processing.

Also, even once you get this all working, you have a few
other problems ahead.  eval() actually tries to evaluate
the expression, as in it doesn't necessarily return a 
string.  send() requires a string, so at the very least 
you had better wrap a str() around the result of eval().
And you better put the eval() call in a try/except block 
so that your whole application doesn't shut down when the
user enters something like "1/0".

Although you'll learn a lot working through this 
exercise, I just wanted to let you know that many others
have been here before and already solved the problems 
you are going to face.  If you're doing this to learn,
great!  More power to you. :-)   If you actually want
a working solution and don't much care to learn how to
do all this, look around for existing solutions that
do what you're trying to do with far more robustness.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list