使用Python 2.7.x中的所有可打印字符对IP地址进行编码 - python

我想使用所有可打印字符将IP地址编码为尽可能短的字符串。根据https://en.wikipedia.org/wiki/ASCII#Printable_characters,它们是代码20hex至7Ehex。

例如:

shorten("172.45.1.33") --> "^.1 9" maybe.

为了使解码容易,我还需要编码的长度始终保持相同。我也想避免使用空格字符,以便将来进行解析。

一个人该怎么做?

我正在寻找在Python 2.7.x中可以使用的解决方案。

到目前为止,我尝试修改Eloims的答案以在Python 2中工作:

首先,我为python 2(https://pypi.python.org/pypi/ipaddress)安装了ipaddress反向端口。

#This is needed because ipaddress expects character strings and not byte strings for textual IP address representations 
from __future__ import unicode_literals
import ipaddress
import base64

#Taken from http://stackoverflow.com/a/20793663/2179021
def to_bytes(n, length, endianess='big'):
    h = '%x' % n
    s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
    return s if endianess == 'big' else s[::-1]

def def encode(ip):
    ip_as_integer = int(ipaddress.IPv4Address(ip))
    ip_as_bytes = to_bytes(ip_as_integer, 4, endianess="big")
    ip_base85 = base64.a85encode(ip_as_bytes)
    return ip_base

print(encode("192.168.0.1"))

现在这失败了,因为base64没有属性'a85encode'。

参考方案

我找到了这个问题,寻找在python 2上使用base85 / ascii85的方法。最终,我发现了几个可以通过pypi安装的项目。我选择了一个叫做hackercodecs的项目,因为该项目特定于编码/解码,而我发现的其他项目只是将实现作为必要的副产品提供的

from __future__ import unicode_literals
import ipaddress
from hackercodecs import ascii85_encode

def encode(ip):
    return ascii85_encode(ipaddress.ip_address(ip).packed)[0]

print(encode("192.168.0.1"))

https://pypi.python.org/pypi/hackercodecs
https://github.com/jdukes/hackercodecs

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

python:ConfigParser对象,然后再阅读一次 - python

场景:我有一个配置文件,其中包含要执行的自动化测试的列表。这些测试是长期循环执行的。   配置文件的设计方式使ConfigParser可以读取它。由于有两个三个参数,因此我需要通过每个测试。现在,此配置文件由script(s1)调用,并且按照配置文件中的列表执行测试。Script(s1)第一次读取配置,并且在每次测试完成后都会执行。阅读两次的要求:由于可能会…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…