2015-05-18 61 views
1

我使用Python的第一次,并且遇到了以下问题,在运行它在树莓派版B +修订版2:错误的文件描述符错误(错误9)树莓

的代码应该设置引脚22(BCM)中断,当按下按钮,停止OS:

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

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


# Define a function to run when an interrupt is called 
def shutdown(pin): 
    call('halt', shell=False) 

gpio.setmode(gpio.BCM) # Set pin numbering to BCM numbering 
gpio.setup(22, gpio.IN) # Set up pin 22 as an input 
gpio.add_event_detect(22, gpio.RISING, callback=shutdown, bouncetime=200) # Set up an interrupt to look for button presses 


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

程序运行正常,当我这样称呼它:

python program.py 

但如果我把它放在t中他的背景是这样的:

python program.py & 

它工作得很好,直到我做任何另一个命令(可以是任何东西(例如。 LS))。 然后停止(但不杀死它)。

我做了一个nohup的输出,这就是我在这:

Traceback (most recent call last): 
    File "haltButton.py", line 19, in <module> 
    loop() # Run the loop function to keep script running 
    File "haltButton.py", line 7, in loop 
    raw_input() 
IOError: [Errno 9] Bad file descriptor 

可有人请点我朝着正确的方向?

回答

3

后台程序不能做raw_input()。这就是后台程序的重点:放弃用户输入,以便shell(或其他程序)可以运行并处理它。

如果你只是想一直运行直到发出信号,只需找到一个不同的方式来做到这一点。几乎什么将工作,除了raw_input。例如,您可以在某些fd上循环使用time.sleepselect.select,或者您可以考虑的其他任何内容,除非尝试从您关闭的fd读取。

+0

哦,我现在明白了,谢谢! 虽然另一个问题: time.sleep使用while循环对吗?那么它就会打破中断的全部目的,而不是经常检查GPIO引脚的while循环。 –

+1

@WilhelmSorban:'time.sleep'不能在while循环中工作,它通过让内核在接下来的1秒内(或者很长时间)不运行你的程序来工作,除非有信号。 – abarnert

+1

@WilhelmSorban:在封面上,这与'raw_input'没什么区别,它在标准输入中包含一个阻塞的'read'调用,它告诉内核不要运行你的程序,直到需要读取文件描述符除非有信号。 – abarnert

相关问题