Raspberry 上 Python(错误 9)中的错误文件描述符错误

Bad file descriptor error in Python (Error 9) on Raspberry

我是第一次使用 Python,遇到了以下问题,而 运行 它在 Raspberry Pi 版本 B+ 修订版 2 上:

代码应该在 pin 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

但是如果我像这样把它放在后台:

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

谁能告诉我正确的方向?

后台程序做不到raw_input()。这就是作为后台程序的全部意义所在:您放弃用户输入,以便 shell(或其他程序)可以 运行 并处理它。

如果您只想 运行 永远 运行 直到发出信号,只需找到一种不同的方法即可。几乎 任何东西 都可以,除了 raw_input。例如,您可以在某些 fd 上循环 time.sleepselect.select,或者除了尝试从您关闭的 fd 中读取之外您能想到的任何其他内容。