2

I'm having some trouble with some code I'm working on. It should be obvious as to what it does in the code. Here is the python code I have:

import RPi.GPIO as gpio
import subprocess
gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(2, gpio.OUT)
p2on = False
while True:
    input_state = gpio.input(18)
    if input_state == False:
        if p2on == False:
            subprocess.call(['say','The light is on'])
            p2on = True
        else:
            subprocess.call(['say','The light is off'])
            p2on = False
    if p2on == True:
        gpio.output(2, True)
    else:
        gpio.output(2, False)

The say command I have thrown in there is just an alias I setup for basic TTS. The say command works on it's own, and I have two .sh scripts that call those same say commands, the code works. However, when I try just calling the command directly as above instead of:

import os
os.system('sh /home/pi/on.sh')

I get an error. The os.system method works, but only if I call another script file, and that's just too messy. The error that I get is:

Traceback (most recent call last):
  File "button.py", line 13, in <module>
    subprocess.call(['say','The light is on'])
  File "/usr/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Any ideas?

  • Are you saying say is an alias, not a command? Is the alias available to the environment you are using? Why not just use the command the alias points to? – joan Jun 26 '15 at 21:21
  • Say just points to Speech.sh in my home directory. I have also tried both a subprocess and system of sh /home/pi/Speech.sh the light is on. Subprocess spat out a very similar error and os.system said there was a syntax error because of an unexpected (. – user32264 Jun 26 '15 at 21:25
  • 1
    Well, I fixed it. Now I feel silly. It wasn't letting me do os.system('./Speech.sh The Light is now on') before, but after I added in os.system('cd /home/pi') before the while loop, it worked. Silly mistake. – user32264 Jun 26 '15 at 21:32
2

Aliases are something your shell interprets and runs. It's not a system call. That's why it works from your .sh scripts, but not this python script.

I would suggest changing your call to:

subprocess.call(['/bin/sh', '-i', '-c', 'say', 'the light is ...')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy