簡體   English   中英

將 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

I am continuing my sojourn into transitioning about 15 (multiple authors/sources) years of Python scripts into Python 3 and have run into an issue that I assume is Python 2.x versus Python 3.x, but could be mistaken on. 代碼如下。

在 2.7x 中,下面的代碼可以正常工作(減去添加的universal_newlines標志)。 這里output是一個元組, output[0]是一個(可能很長的)浮點數和整數字符串(例如 output 下面的代碼)。 在 3.x/8 中,cpu 格式有點混亂,無法調用。 有趣的是,這step似乎還不錯。

我認為浮動的處理方式可能有所不同,但在閱讀它時,沒有什么是顯而易見的。 所以,歡迎提出建議。

 cmd = """grep CPU %s | gawk '{print $8, $11}' """ % (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.7x:

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(map(float,lines.split()[0::2]))

需要改為

cpu = numpy.array(list(map(float,lines.split()[0::2])))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM