我正在为本地网络写一个聊天程序。我希望能够识别计算机,并获得用户设置的计算机名称与Python。
当前回答
在某些系统上,主机名是在环境中设置的。如果是这样的话,操作系统模块可以通过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.
其他回答
在某些系统上,主机名是在环境中设置的。如果是这样的话,操作系统模块可以通过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.
我需要在PyLog conf文件中使用的PC的名称,并且套接字库不可用,但操作系统库可用。
对于Windows,我使用的是:
os.getenv('COMPUTERNAME', 'defaultValue')
哪里defaultValue是一个字符串,以防止None返回
从至少python >= 3.3:
你可以使用字段nodename,避免使用数组索引:
os.uname().nodename
虽然,甚至os的文档。Uname建议使用socket.gethostname()
使用socket.getfqdn()获取完全限定的主机名
import socket
print socket.getfqdn()
Socket.gethostname()可以做什么
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行