我正在为本地网络写一个聊天程序。我希望能够识别计算机,并获得用户设置的计算机名称与Python。
当前回答
Socket.gethostname()可以做什么
其他回答
在某些系统上,主机名是在环境中设置的。如果是这样的话,操作系统模块可以通过os.getenv把它从环境中拉出来。例如,如果HOSTNAME是包含你想要的内容的环境变量,下面将得到它:
import os
system_name = os.getenv('HOSTNAME')
Update: As noted in the comments, this doesn't always work, as not everyone's environment is set up this way. I believe that at the time I initially answered this I was using this solution as it was the first thing I'd found in a web search and it worked for me at the time. Due to the lack of portability I probably wouldn't use this now. However, I am leaving this answer for reference purposes. FWIW, it does eliminate the need for other imports if your environment has the system name and you are already importing the os module. Test it - if it doesn't work in all the environments in which you expect your program to operate, use one of the other solutions provided.
Socket.gethostname()可以做什么
这两个都是非常可移植的:
import platform
platform.node()
import socket
socket.gethostname()
任何使用HOST或HOSTNAME环境变量的解决方案都不能移植。即使它在您的系统上运行时可以工作,但在cron等特殊环境中运行时可能无法工作。
从至少python >= 3.3:
你可以使用字段nodename,避免使用数组索引:
os.uname().nodename
虽然,甚至os的文档。Uname建议使用socket.gethostname()
如果我没猜错,你是在找插座。gethostname功能:
>> import socket
>> socket.gethostname()
'terminus'
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录