虽然这是一个非常常见的错误,但我还没有找到解决此特定问题的方法。
我有一个带有行
的脚本line = int(ser.readline())
有时(不是每次!)当我运行此脚本时都会收到此错误:
Traceback(most recent call last):
File "./project.py", line 28, in <module>
line = int(ser.readline())
ValueError: invalid literal for int() with base 10:' '
当发生这种情况时,我可以简单地重启脚本,它运行正常。
这里发生了什么?有没有办法防止这种情况发生?
这里是完整的脚本,供参考。违规代码在第28行。
#!/usr/bin/python
import time
import serial
import subprocess
# -------------function for videos-------------
def play_vid_nonblocking(num):
return subprocess.Popen(["xterm", "-fullscreen", "-e", "omxplayer", "-o", "hdmi", "-r", "/home/pi/Ligia/{:02d}.mp4".format(num)])
# -------------sensor setup-------------
ser = serial.Serial('/dev/ttyACM0', 9600)
# -----------------------------------------
num_videos = 10
i = 1
p = None
time.sleep(60)
while True:
line = int(ser.readline())
print line
if line < 750:
if p is None or p.poll() is not None:
p = play_vid_nonblocking(i)
time.sleep(60)
i = i + 1
if i > num_videos:
i = 0
else:
pass
else:
pass
else:
pass
ser.close()
答案 0 :(得分:0)
try:
line = int(line)