我正在Mac OS上的python3中运行一个子进程,以从保存在本地目录中的许多图像中检索EXIF图像数据。
该代码间歇性地工作。子进程几乎每隔第3次调用都会返回字节对象(如预期的那样),只有它为空b''。
该故障并非特定于任何特定的图像文件(更改)。
我尝试了两个版本的代码,一个版本在其中调用Popen.wait(..)(示例在下面查找纬度),另一个版本在其中立即调用.communicate()(在下面查找经度)。
print('.......========.......')
try:
cmdLat = "mdls \"" + imagePath + "\" | grep Latitude | awk '{print $3}'"
subprocess = Popen(cmdLat, shell=True, stdout=PIPE)
Popen.wait(subprocess)
lat = subprocess.communicate()[0]
latFloat = float(lat.decode())
except Exception as e:
print("Failed finding latitude, exception:", e)
print("lat value: ", lat)
try:
cmdLon = "mdls \"" + imagePath + "\" | grep Longitude | awk '{print $3}'"
lon = (Popen(cmdLon, shell=True, stdout=PIPE).communicate()[0])
lonFloat = float(lon.decode())
except Exception as e:
print("Failed finding longitude, exception:", e)
print("lon value: ", lat)
尝试1个结果:
.......========.......
IMG_0149.JPG has been successful
.......========.......
IMG_0161.JPG has been successful
.......========.......
IMG_0377.JPG has been successful
.......========.......
Failed finding latitude, exception: could not convert string to float:
lat value: b''
Failed finding longitude, exception: could not convert string to float:
lon value: b''
尝试2个结果:
.......========.......
IMG_0149.JPG has been successful
.......========.......
IMG_0161.JPG has been successful
.......========.......
IMG_0377.JPG has been successful
.......========.......
IMG_0007.JPG has been successful
.......========.......
Failed finding lattitude, exception: could not convert string to float:
lat value: b''
Failed finding longitude, exception: could not convert string to float:
lon value: b''
答案 0 :(得分:1)
这可能是您引用引起麻烦的文件名的方式,或者可能是迈克尔·布彻(Michael Butscher)建议的时机。我尝试自己写一个解决方案,发现我的大多数照片都没有坐标。
这是我的解决方案,请告诉我它是否适合您。请注意,对于那些没有坐标的图片,lat=="(null)"
和lon="(null)"
。对于具有坐标的坐标,lat
和lon
将是浮点。
#!/usr/bin/env python3
import pathlib
import subprocess
def main():
""" Entry """
for pic_file in pathlib.Path('.').glob('*.jpg'):
print('-' * 72)
print(pic_file)
command = ['mdls',
'-name', 'kMDItemLatitude',
'-name', 'kMDItemLongitude',
str(pic_file)]
output = subprocess.check_output(command, encoding='utf-8')
# Sample output
# kMDItemLatitude = (null)
# kMDItemLongitude = (null)
# or
# kMDItemLatitude = 46.75725833333333
# kMDItemLongitude = -71.28605666666667
print(output)
# Parse the output
lines = output.splitlines()
values = [line.split()[-1] for line in lines]
print(values)
# Convert to float
try:
lat, lon = [float(value) for value in values]
except ValueError:
lat, lon = values
print('Latitude =', lat)
print('Logitude =', lon)
if __name__ == '__main__':
main()
grep
和awk
命令,因为我想自己解析值subprocess
函数的输出将返回原始字节数组,我使用encoding='utf-8'
将其转换为Python 3字符串。