Bad file descriptor error in Python (Error 9) on Raspberry
Question: I am working with Python for the first time, and encountered the following
issue, while running it on a Raspberry Pi Version B+ rev 2:

The code is supposed to set an interrupt on pin 22 (BCM), and when a button is
pressed, halt the 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
    

The program runs fine when I call it like this:

    
    
    python program.py
    

But if I put it in the background like this:

    
    
    python program.py &
    

it works fine, until I do any another command (can be anything (eg. ls)). Then
it stops (but doesn't kill it).

I did a nohup output, and this is what I have in it:

    
    
    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
    

Can anybody please point me to the right direction?


Answer: A background program can't do `raw_input()`. That's the whole point of being a
background program: you give up user input so the shell (or some other
program) can run and handle it.

If you just want to run forever until signaled, just find a different way of
doing that. Almost _anything_ will work, except `raw_input`. For example, you
can loop over `time.sleep`, or `select.select` on some fd, or anything else
you can think of except for trying to read from an fd that you closed.

