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?

  • 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 at 2: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 at 2:22
  • I've tried both of those different commands; they both give the same error. – Jim421616 Jul 24 at 3:22
  • exactly the same error? – Jaromanda X Jul 24 at 4:06
  • 1
    Di you try the the whole path /usr/bin/vcgencmd or using Popen rather than call? – PiEnthusiast Jul 24 at 5:56
up vote 2 down vote accepted

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.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.