我已经提到了关于同一错误的其他问题。但是我不想指定编码,只想跳到下一行。是否可以ignore errors
在readline()
旁边看?
我正在使用find
实用程序来获取30天以上的文件。并返回具有完整路径的文件。但是,当另一个用户将代码用于另一条路径时,他得到了编码错误。因此,如果有错误,stdout.readline()
则我想跳过该行,然后移至下一个。是否stdout.readline()
允许跳过错误之类的东西?
同样在这种给定的find
结果场景中,我可以使用utf-8
编码并确保将读取的路径没有错误吗?
find_cmd = ['find', '/a/b', '-mtime', f'+30', '-readable', '-type', 'f', '-print']
j = ' '.join(find_cmd)
proc = subprocess.Popen(j, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
file = proc.stdout.readline().replace('\n', '') #Error here 'utf-8' codec can't decode byte 0xe4 in position 1478: invalid continuation byte
if not file: break
movefile(file)
如果find
不能保证来自的输出为UTF-8,请不要使用universal_newlines=True
(又名text=True
Python 3.7及更高版本)。
你可以选择在阅读时进行解码,如果需要的话,可以跳过无效的UTF-8条目。
另外,出于对的热爱$dmr
,请勿join
仅将你的最佳列表放在一起,以免不必要地浪费在shell=True
列表上。
最后,如果你不想让错误消息像文件名一样出现,请不要重定向stderr
到。根本就不要完全重定向,以使其在控制台上显示,或者如果要完全丢弃它们,则直接指向。stdout
find
stderr
stderr
subprocess.DEVNULL
find_cmd = [
'find', '/a/b', '-mtime', f'+30', '-readable',
'-type', 'f', '-print']
proc = subprocess.Popen(find_cmd, stdout=subprocess.PIPE, check=True)
while True:
filename = proc.stdout.readline().replace(b'\n', b'')
if not filename:
break
try:
file = filename.decode('utf-8')
movefile(file)
except UnicodeDecodeError:
logging.info('Skipping non-UTF8 filename %r' % filename)
你会注意到我添加check=True
到subprocess.Popen()
;如果你想忽略find
故障,也许可以再解决一次。
如果您的文件系统不是UTF-8干净的,我怀疑是有问题的,或者至少是险恶的。
我在使用列表时遇到了一些错误(我认为在参数中使用转义字符),所以我做
join
了使其工作。应该有另一种正确的方法来解决此问题。错误可能在
readline()
还是在replace()
?。因为我在同一行中出现错误,并且这里的try块也位于错误行之后..错误是
.decode()
当您说Python时会暗中为您效劳text=True
。现在,我们decode
稍后进行显式处理,并仅从该操作中捕获任何错误。也许也可以text=True
在stackoverflow.com/questions/4256107/中看到有关该部分的内容。解码后执行此操作。立即删除换行符很有意义。因此
file.startswith
,filename.startswith
您可以使用代替(尽管我想您可以对解码后的值使用相同的变量名)。