4

I'm working on a project which will use a PIR motion sensor to turn on a connected HDMI monitor when there's someone in the room, and turn it off when they leave. I'm new to Linux, but not to Python. My code so far is:

import RPi.GPIO as GPIO
import time
from subprocess import call

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)
while true:
    i = GPIO.input(11)
    if i ==0:
        print("Screen off", i)
        call("vcgencmd display_power 0")
        time.sleep(1)
    elif i ==1:
        print("Screen on", i)
        call("vcgencmd display_power 1")
        time.sleep(30)

If I just type in vcgencmd display_power 0 or vcgencmd display_power 1 to a terminal, the commands work fine, but this script produces a

FileNotFoundError: [Errno 2] No such file or directory: 'vcgencmd display_power 1'

I've found questions asking how to turn the screen on and off, and all of these seem to do it from the command line, not a Python script.

How can I run the command from the Python script?

Jim421616
  • 185
  • 1
  • 1
  • 7
  • I don't know python well, but does call take more than one argument? e.g., call("vcgencmd", "display_power", "0") - i.e. the first argument is the command, and the subsequent arguments are the command line parameters passed to the command – Jaromanda X Jul 24 '18 at 02:21
  • 1
    having looked, it could be call(["vcgencmd", "display_power", "0"]) - it's very hard getting documentation for python for something like call! – Jaromanda X Jul 24 '18 at 02:22
  • I've tried both of those different commands; they both give the same error. – Jim421616 Jul 24 '18 at 03:22
  • exactly the same error? – Jaromanda X Jul 24 '18 at 04:06
  • 1
    Di you try the the whole path /usr/bin/vcgencmd or using Popen rather than call? – PiEnthusiast Jul 24 '18 at 05:56
  • @PiEnthusiast no I just called the function. Thanks for pointing that out; what would the syntax for that be? Like I said, I’m pretty new to Linux and I haven’t tried calling the command line with python before. – Jim421616 Jul 24 '18 at 06:05

1 Answers1

3

Inspired by @PiEnthusiast's and @Jaramonda's answers, I changed the calls to the function to read

call(["/usr/bin/vcgencmd", "display_power", "0"])

and it works great! I didn't understand how Linux terminal commands worked to be routed through Python scripts.

Jim421616
  • 185
  • 1
  • 1
  • 7
  • 1
    To do what you were originally attempting, you can just specify shell=True as an argument. Also note that call() is considered a legacy API since Python 3.5. The new run() method simplifies and harmonizes the API somewhat, and in this case it would just be run('vcgencmd display_power 0', shell=True) . – Peter Hansen Jul 21 '19 at 15:27
  • for me this just prints out "display_power=1" whether I call it with 1 or 0 and doesn't turn the screen on or off – Charon ME Dec 10 '22 at 17:27