I am trying to get the hostname in Python. In linux, if I type hostname on the command prompt I get

root@phxdbx45:/home/david/zkpython# hostname
phxdbx45

But if I type hostname -f then I get below full qualified hostname in ubuntu and that's what I need from Python as well.

root@phxdbx45:/home/david/zkpython# hostname -f
phxdbx45.phx.host.com

I know in Python we can use below code but it does not give me fully qualified host name. It gives me the output of hostname as I mentioned above.

#!/usr/bin/python

import socket

hostname = socket.gethostname()
print hostname

Is there any way to get fully qualified hostname in Python which is reliable and correct?

有帮助吗?

解决方案

Use the descriptively-named function socket.getfqdn():

>>> import socket   
>>> socket.getfqdn()
'phxdbx45.phx.host.com'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top