如何在 Python 中获取完全限定的主机名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20792499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get fully qualified host name in Python?
提问by arsenal
I am trying to get the hostname in Python. In linux, if I type hostnameon the command prompt I get
我正在尝试在 Python 中获取主机名。在 linux 中,如果我hostname在命令提示符下输入,我会得到
root@phxdbx45:/home/david/zkpython# hostname
phxdbx45
But if I type hostname -fthen I get below full qualified hostname in ubuntu and that's what I need from Python as well.
但是,如果我输入,hostname -f那么我会在 ubuntu 中得到低于完全限定的主机名,这也是我从 Python 中需要的。
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 hostnameas I mentioned above.
我知道在 Python 中我们可以使用下面的代码,但它没有给我完全限定的主机名。它给了我hostname上面提到的输出。
#!/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?
有什么方法可以在 Python 中获得可靠且正确的完全限定主机名?
采纳答案by rightfold
Use the descriptively-named function socket.getfqdn():
使用描述性命名的函数socket.getfqdn():
>>> import socket
>>> socket.getfqdn()
'phxdbx45.phx.host.com'

