標準庫
Python擁有一個強大的標準庫。Python語言的核心只包含數字、字符串、列表、字典、文件等常見類型和函數,而由Python標準庫提供了系統管理、網絡通信、文本處理、數據庫接口、圖形系統、XML處理等額外的功能。
Python標準庫的主要功能有:
1.文本處理,包含文本格式化、正則表達式匹配、文本差異計算與合并、Unicode支持,二進制數據處理等功能
2.文件處理,包含文件操作、創建臨時文件、文件壓縮與歸檔、操作配置文件等功能
3.操作系統功能,包含線程與進程支持、IO復用、日期與時間處理、調用系統函數、日志(logging)等功能
4.網絡通信,包含網絡套接字,SSL加密通信、異步網絡通信等功能
5.網絡協議,支持HTTP,FTP,SMTP,POP,IMAP,NNTP,XMLRPC等多種網絡協議,并提供了編寫網絡服務器的框架
6.W3C格式支持,包含HTML,SGML,XML的處理。
7.其它功能,包括國際化支持、數學運算、HASH、Tkinter等
python利用標準庫獲取本地IP
這個最簡單,但是也最不靠譜,依賴hosts文件,如果hosts文件沒配置,一般容易獲取到127.0.0.1
import socketsocket.gethostbyname(socket.gethostname())
import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect(("8.8.8.8", 80))print(s.getsockname()[0])s.close()import socketalias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(/"127./")][:1], [[(s.connect((/"8.8.8.8/", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'" print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]) print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0]) print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]) print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])import osimport socket if os.name != "nt": import fcntl import struct def get_interface_ip(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) def get_lan_ip(): ip = socket.gethostbyname(socket.gethostname()) if ip.startswith("127.") and os.name != "nt": interfaces = [ "eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0", ] for ifname in interfaces: try: ip = get_interface_ip(ifname) break except IOError: pass return ip
新聞熱點
疑難解答