python socket usage

Gary Herron gherron at islandtraining.com
Thu Aug 16 04:20:38 EDT 2007


markacy wrote:
> On 16 Sie, 09:42, O uz Yar mtepe <comp.... at gmail.com> wrote:
>   
>> Is it possible to send a data object like a tuple or a list in socket
>> programming? If so how? It seems with socket module it is only possible to
>> send strings.
>>
>> --
>> O uz Yar mtepehttp://www.yarimtepe.com/en
>>     
>
> Hi Oguz,
>
>    why don't you make a string out of your tuple, or list, send it via
> socket and make a tuple/list again?
>
>   
>>>> x = (1,2,3,4,5,6,7,)
>>>> type(x)
>>>>         
> <type 'tuple'>
>   
>>>> y = str(x)
>>>> type(y)
>>>>         
> <type 'str'>
>   
>>>> print y
>>>>         
> (1, 2, 3, 4, 5, 6, 7)
>   
>>>> z = tuple(y)
>>>> type(z)
>>>>         
> <type 'tuple'>
>   
Sure it's a tuple, but did you look at it?  Turning a sequence (which is
what a string is after all) into a tuple is an easy operation, but it's
surely not what you want here.

>>> x = (1,2,3,4,5,6,7)
>>> s = str(x)
>>> t = tuple(s)
>>> t
('(', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5',
',', ' ', '6', ',', ' ', '7', ')')

If you want to turn a string representation of an object back into an
object, you must eval the string. 
Moreover, if the tuple contains things other than simple integers (float
of strings of whatever) the string represtnataion of the object may not
be able to recover the original object accurately.  Worse yet, an eval
of an arbitrary string is a HUGE security hole.

If you really want to send any Python object through a socket, look up
the Pickle and cPickle modules.  These will marshal (as it's called) any
Python object of any type and complexity into a byte string which can be
sent across a socket.  On the receiving end of the socket, the byte
string can be turned back into an equivalent Python object.

Gary Herron



>
> Cheers,
> Marek
>
>   




More information about the Python-list mailing list