python - Python 在 rc.local 中运行并不一致地写入文件
问题描述
我试图让我的树莓派在启动时运行代码,这将允许我用游戏手柄控制电机驱动器。我的代码在正常运行时工作,但从 rc.local 运行时不起作用
我创建了一个版本(见下文),应该写“没有连接游戏手柄。请打开它!” 每次它搜索游戏手柄时,一旦找到它应该在每次按下该按钮时将“Y”或“B”写入同一个文件。
它总是写着“没有连接游戏手柄。请打开它!” 到文件中,但之后不会写入按下的按钮。同样,当我不是从 rc.local 运行它时,它工作正常。
在线寻找解决方案我看到python在后台运行时无法正确写入文件。我尝试在 rc.local 中将它作为“python -u”运行,将“#!/usr/bin/python -u”添加到文件顶部,并使用 f.flush() 和 sys.stdout 刷新它.flush() 以不同的组合。
这是我的 rc.local 文件
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#sudo python /home/pi/sample.py &
python -u /home/pi/Desktop/RPi_Bluetooth_RoboClaw/On_Boot_Motor.py &
exit 0
这是我正在运行的代码的相关部分。它首先确保游戏手柄已连接,然后应该开始将输出写入文件。
#!/usr/bin/python -u
import time
from roboclaw import Roboclaw
from evdev import InputDevice, categorize, ecodes
import fnmatch
import os
f = open("/home/pi/Desktop/Output.txt","w")
gamepadConnect = False
while(not gamepadConnect):
try:
gamepad = InputDevice('/dev/input/event0')
gamepadConnect = True
except:
f.write("No Gamepad Connected. Please turn it on! \n")
time.sleep(0.5)
f.close()
#button code variables as found for 8bitdo gamepad
bBtn = 305
yBtn = 308
while(True):
f = open("/home/pi/Desktop/Output.txt","a")
try:
for event in gamepad.read_loop():
if event.type == ecodes.EV_KEY:
if event.value == 1:
#if the Y button is pressed
if event.code == yBtn:
#Turn Left
f.write("Y")
#if the B button is pressed
elif event.code == bBtn:
#Inch
f.write("B")
except KeyboardInterrupt:
break
f.flush()
sys.stdout.flush()
f.close()
本质上,我想弄清楚为什么它只写“没有连接游戏手柄。请打开它!” 而不是按下按钮,理想情况下,我想要一个可以在向电机驱动程序发送字节时使用的解决方案,例如关于 rc.local 如何运行文件的一些信息。
解决方案
推荐阅读
- jenkins - Jenkins在使用自定义工作区时排除目录
- android - 如何让日历根据应用程序内的语言更改标题和日期名称?
- python - 优化字节数组转义性能python
- node.js - Node.js (Express) 动态插入元标记错误:未捕获的 SyntaxError: Unexpected token '<'
- android - 如何在 ListView 中加载音频文件?
- javascript - Javascript / Jquery 从部分选择描述符中提取整个 CLASS 描述符
- javascript - 附加标签未出现在图表 d3.js 中
- python - 检查元素是否已经在列表中
- python - 针对不同平台交叉编译python库
- nuxt.js - Cloudinary Nuxt 模块:未知元素 cld-image