简体   繁体   English

在后台运行python脚本-Raspbian

[英]Running python script in the background - Raspbian

I have recently constructed a small robot car using my raspberry pi 3 with raspbian stretch. 我最近使用树莓派的树莓派3构建了一辆小型机器人车。 I am currently at the point where I can drive the car around using an xbox360 controller plugged into the pi USB port. 目前,我可以使用插入pi USB端口的xbox360控制器来开车。 My issue is that I do not like having to ssh into the pi and run the script I have written in order to use the robot (robot.py). 我的问题是,我不喜欢必须ssh进入pi并运行我编写的脚本才能使用机器人(robot.py)。

What I would like to do is have a script running in the background which works something like this: 我想做的是在后台运行一个脚本,其工作方式如下:

#while true
    #if joystick is detected
        #robotoffflag=true
        #if startup button is pressed on the joystick && robotoffflag
            #robotoffflag=false
            #run robot.py to control the robot
            #robot.py already has controls for shutting down the robot
            #which disables the motors and sets robotoffflag to true

This way, if my pi is powered up, I can at any point just press a button on my controller and start using the robot. 这样,如果我的pi上电,我可以随时按控制器上的一个按钮并开始使用机器人。 Then when I am done, press another button on the controller to disable the robot. 然后,当我完成操作时,按控制器上的另一个按钮以禁用机器人。

My question is, am I going about this in the right way? 我的问题是,我是否要以正确的方式解决? Having a script running in the background which is basically an infinite loop with conditionals inside seems silly to me. 在后台运行脚本,基本上是一个无限循环,内部有条件,这对我来说很愚蠢。 Would it be better to have something more event driven? 有更多的事件驱动会更好吗?

Here is something I might do, thought a bit of a hack. 我可能会做些事,以为有些hack。 Put the python code in to a loop, adding a very short sleep at the end of each loop to limit cpu usage. 将python代码放入一个循环中,在每个循环结束时添加一个非常短的睡眠以限制cpu的使用。 Then run the python script inside a session of tmux, detached of course. 然后在一个tmux会话中运行python脚本,这当然是分离的。 The python script will then run until the tmux session is killed, even if your ssh session exits. python脚本将一直运行,直到tmux会话被杀死,即使您的ssh会话退出了。 tmux is just an example utility, by the way. 顺便说一下,tmux只是一个示例实用程序。 There are others. 还有其他 Of course you could get fancy and implement the loop within a signal-and-wait mechanism, which would wait for a signal from your controller, then launch that from an operating system daemon. 当然,您可能会幻想并在信号等待机制中实现循环,该机制将等待控制器发出的信号,然后从操作系统守护程序启动该信号。 Depends how deep you want to go ... 取决于你想走多深...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM