【发布时间】:2019-04-16 21:05:08
【问题描述】:
我正在尝试从我的 python 应用程序中调用一个 bash 命令来更改我的触摸屏上的背景光。 python 应用程序将在我的 Raspberry Pi (Rasbian/stretch) 上运行。
在终端中运行 bash 命令并不复杂:sudo sh -c "echo 80 > /sys/class/backlight/rpi_backlight/brightness" 肯定会使屏幕变暗(这是我想要的)。但是我怎样才能在我的 python 应用程序中使用sudo 脚本呢? (我知道有几个线程在谈论这个,例如这个Using sudo with Python script,但我不明白在实践中如何做到这一点?)
这是我的代码:
#!/usr/bin/env python3
import subprocess
import time
import sys
# read arguments from the run command:
# idle time before dim (in seconds)
idleTimeBeforeDimMS = int( sys.argv[1] )*1000
# brightness when dimmed (between 0 and 255)
brightnessDimmed = int( sys.argv[2] )
brightnessFull = 255
def get(cmd):
# just a helper function
return subprocess.check_output(cmd).decode("utf-8").strip()
isIdle0 = False
stateChanged = False
timeIntervalToWatchChangesS = 100 / 1000
while True:
time.sleep( timeIntervalToWatchChangesS )
currentIdleTimeMS = int( get("xprintidle") )
isIdle = currentIdleTimeMS > idleTimeBeforeDimMS
stateChanged = isIdle0 != isIdle
if isIdle and stateChanged:
# idling
bashCommand = "echo 50 > /sys/class/backlight/rpi_backlight/brightness"
subprocess.run(['bash', '-c', bashCommand])
elif not isIdle and stateChanged:
# active
bashCommand = "echo 255 > /sys/class/backlight/rpi_backlight/brightness"
subprocess.run(['bash', '-c', bashCommand])
# set current state as initial one for the next loop cycle
isIdle0 = isIdle
如果我直接运行脚本,我的 bash 命令会出错:bash: /sys/class/backlight/rpi_backlight/brightness: Permission denied。没关系,我知道我缺少sudo-部分,但我应该把它放在哪里?
【问题讨论】:
-
就像在
/sys中一样,您应该可以使用sysctl进行设置,这将使命令更简单,因为它以sudo sysctl开头,没有bash 和echo。