1

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

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.

  • 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 at 15:27

Your Answer

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

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