1

I am trying to execute this script to get the hostname of my laptop

I use Windows7 64bit and Python 3.6.4

I have tried this code in Python IDE and it worked . This error occurred in PyCharm

import socket
c = socket.gethostname()
print(c)

Do you have any solutions?

Hamada Dz
  • 11
  • 4
  • 5
    did you created file `socket.py` or folder `socket` ? If you have `socket.py` then Python imports your file instead of module `socket` and it can't find `gethostname` in your file. Rename your file. – furas Aug 14 '19 at 11:07
  • linking to https://stackoverflow.com/a/3124164/1358308 as @furas suggestion is almost certainly right – Sam Mason Aug 14 '19 at 11:33

3 Answers3

1

It's very likely that your file is named as socket.py.

Then when you import socket, it will import the current file instead of the python socket module.

Rename your file to another name and rm -rf socket.pyc (to remove the compiled bytecode generated by previous executions).

Cassie Xu
  • 56
  • 4
0

When I was importing matplotlib.pyplot, this error was coming - AttributeError: module 'socket' has no attribute 'gethostname'

But I had created a file socket.py once ,I removed this file, this issue was fixed

0

I had the same problem when I used a file named "socket.py" so I renamed the file to another name and it's working now.

  • 2
    When submitting an answer, please check the other answers to make sure your answer contains something unique. In this case it appears your answer contains only information that was already available in other answers. – President James K. Polk Nov 01 '22 at 00:53