将 Python 2.7x 转换为 3.x 兼容性问题:格式和 subprocess.Popen、numpy.array 和浮动问题
Converting Python 2.7x to 3.x compatability issues: Issues with format and subprocess.Popen, numpy.array, and floats
我将继续我的逗留之旅,将大约 15(多个 authors/sources)年的 Python 脚本转换为 Python 3,并将 运行 转换为我 假设 是Python 2.x 而不是Python 3.x,但可能会被误认为。下面的代码。
在 2.7x 中,下面的代码工作正常(减去添加的 universal_newlines
标志)。这里 output
是一个元组, output[0]
是一个(可能很长)浮点数和整数字符串(代码下面的示例输出)。在 3.x/8 中,cpu 格式有点混乱,结果无法调用。有趣的是 step
似乎 就好了。
我认为浮动的处理方式可能有所不同,但在阅读它时,没有什么是显而易见的。所以,欢迎提出建议。
cmd = """grep CPU %s | gawk '{print , }' """ % (logfile)
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
output = p.communicate()
lines = output[0]
cpu = numpy.array(map(float, lines.split()[0::2]))
step = numpy.array(lines.split()[1::2], dtype=int)
Python 2.7 倍:
output[0]
<type 'tuple'>
<type 'str'>
36.3838 745701
29.4391 745702
23.4954 745703
22.6346 745704
Python 3.8x:
output [0]
<class 'tuple'>
<class 'str'>
42.3777 139371
41.811 139372
44.1033 139373
43.0248 139374
所以,这就是答案
cpu = numpy.array(地图(浮动, lines.split()[0::2]))
需要改为
cpu = numpy.array(列表(地图(浮动, lines.split()[0::2])))
我将继续我的逗留之旅,将大约 15(多个 authors/sources)年的 Python 脚本转换为 Python 3,并将 运行 转换为我 假设 是Python 2.x 而不是Python 3.x,但可能会被误认为。下面的代码。
在 2.7x 中,下面的代码工作正常(减去添加的 universal_newlines
标志)。这里 output
是一个元组, output[0]
是一个(可能很长)浮点数和整数字符串(代码下面的示例输出)。在 3.x/8 中,cpu 格式有点混乱,结果无法调用。有趣的是 step
似乎 就好了。
我认为浮动的处理方式可能有所不同,但在阅读它时,没有什么是显而易见的。所以,欢迎提出建议。
cmd = """grep CPU %s | gawk '{print , }' """ % (logfile)
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
output = p.communicate()
lines = output[0]
cpu = numpy.array(map(float, lines.split()[0::2]))
step = numpy.array(lines.split()[1::2], dtype=int)
Python 2.7 倍:
output[0]
<type 'tuple'>
<type 'str'>
36.3838 745701
29.4391 745702
23.4954 745703
22.6346 745704
Python 3.8x:
output [0]
<class 'tuple'>
<class 'str'>
42.3777 139371
41.811 139372
44.1033 139373
43.0248 139374
所以,这就是答案
cpu = numpy.array(地图(浮动, lines.split()[0::2]))
需要改为
cpu = numpy.array(列表(地图(浮动, lines.split()[0::2])))