python loop():raw_input()EOFError:读取一行时的EOF

时间:2014-10-01 07:40:26

标签: python raspberry-pi

这是脚本(/shutdown.py)。它监视按钮按下,如果按下按钮超过3秒,它将运行poweroff命令。

#!/usr/bin/python

# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
from time import sleep
import RPi.GPIO as gpio
import time

# Define a function to keep script running
def loop():
    raw_input()

# Define a function to run when an interrupt is called
def shutdown(pin):
    button_press_timer = 0
    while True:
        if (gpio.input(17) == False) : # while button is still pressed down
            button_press_timer += 1 # keep counting until button is released
            if button_press_timer == 3:
                #print "powering off"
                call('poweroff', shell=True)
            sleep(1)
        else: # button is released, figure out for how long
            #print "Poga atlaista. nospiesta bija " + str(button_press_timer) + " sekundes"
            #button_press_timer = 0
            return
#       sleep(1) # 1 sec delay so we can count seconds
#    print "powering off"

gpio.setmode(gpio.BCM) # Use BCM GPIO numbers
gpio.setup(17, gpio.IN, pull_up_down=gpio.PUD_UP) # Set up GPIO 17 as an input
gpio.add_event_detect(17, gpio.FALLING, callback=shutdown, bouncetime=200) # Set up an interrupt to look for button presses

loop() # Run the loop function to keep script running

如果我从/shutdown.py这样的控制台运行脚本一切都很好。检测到按钮按下并初始化系统关闭。但是,如果我将该脚本添加到/etc/rc.local(/shutdown.py&),那么它在启动时会因此错误而失败:

Traceback (most recent call last):
  File "/shutdown.py", line 35, in <module>
    loop() # Run the loop function to keep script running
  File "/shutdown.py", line 11, in loop
    raw_input()
EOFError: EOF when reading a line

如果我注释掉loop()行,则没有错误,脚本不会在后台运行。我只是启动并退出并且没有检测到按钮按下。那么,我如何在启动时运行该脚本并继续在后台运行?

修改

我不是python guru,我认为loop()是python内部函数。现在我看到它被定义为调用raw_input()的函数。我发现并修改了该脚本以满足我的需求。 感谢。

1 个答案:

答案 0 :(得分:1)

你真正需要的是一个在后台运行的Python守护进程。你试图使用的raw_input方法看起来像是一个丑陋的黑客。

查看python-daemon包,这完全适合您的用例,并且使用起来非常简单。还有{3}支持Python 3。

安装python-daemon后,将此行添加到脚本的开头

import daemon

然后使用以下代码替换脚本末尾的loop()调用:

with daemon.DaemonContext():
    while True:
        time.sleep(10)

此代码未经测试,但您明白了。