Jeff Abrahamson on 20 Oct 2004 00:05:03 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] python and sockets, weird error


On Tue, Oct 19, 2004 at 03:07:03PM -0400, Jeff Abrahamson wrote:
>   [65 lines, 221 words, 1602 characters]  Top characters: eto\nsanr
> 
> I'm trying to send a UDP packet in python.
> 
> Below is a short code snippet I pulled from the web.  It looks right
> to me.  Other examples look basically the same.
> 
> When I run it, I get an error, "AF_INET" is not defined.
> 
> Anyone see what I might be doing wrong?
> 
> BTW, is there a difference between the "import socket" and "from
> socket import *" ?  I had thought they were the same thing, pick one.
> But I've seen some code on the net recently that does both.
> 
> Thanks in advance.
> 
>     jeff@asterix:hw2a-jeffa $ ./s.py
>     Traceback (most recent call last):
>       File "./s.py", line 3, in ?
> 	import socket
>       File "[...path...]/socket.py", line 13, in ?
> 	UDPSock = socket(AF_INET, SOCK_DGRAM)
>     NameError: name 'AF_INET' is not defined
>     jeff@asterix:hw2a-jeffa $

The problem, it turns out, was that I named my test file socket.py,
not realizing that python first looks in the current directory for
imports.  Of course, you couldn't have known that, because I showed
the name above as s.py.  I don't remember why I changed it.  Probably
I forgot to copy and paste the command line and figured it didn't
matter.  Fool that I am.

The answer to my other question, about the difference between import
and from...import seems to be related to name space.  Here's a
sample.  Note how AF_INET moves to the global name space from the
socket namespace.

    jeff@asterix:jeff $ python
    Python 2.3.4 (#2, Jul  5 2004, 09:15:05)
    [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import socket
    >>> AF_INET
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'AF_INET' is not defined
    >>> socket.AF_INET
    2
    >>>
    jeff@asterix:jeff $ python
    Python 2.3.4 (#2, Jul  5 2004, 09:15:05)
    [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from socket import *
    >>> AF_INET
    2
    >>> socket.AF_INET
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: type object '_socketobject' has no attribute 'AF_INET'
    >>>
    jeff@asterix:jeff $

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>    +1 215/837-2287
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

 A cool book of games, highly worth checking out:
 http://www.amazon.com/exec/obidos/ASIN/1931686963/purple-20

Attachment: signature.asc
Description: Digital signature