sudo 在 subprocess.run 中的什么位置? [英] Where to put sudo in subprocess.run?
问题描述
我正在尝试从我的 Python 应用程序调用 bash 命令,以更改触摸屏上的背景灯.python 应用程序将在我的 Raspberry Pi(Rasbian/stretch)上运行.
I am trying to invoke a bash command from my python application in order to change background light on my touch screen. The python application will run on my Raspberry Pi (Rasbian/stretch).
在终端中运行 bash 命令并不复杂:sudo sh -c "echo 80 >/sys/class/backlight/rpi_backlight/brightness"
肯定会使屏幕变暗(这是我想要的是).但是我如何在我的 python 应用程序中 sudo
脚本?(我知道有几个线程在谈论这个,例如这个 将 sudo 与 Python 脚本一起使用,但我不明白如何在实践中做到这一点?)
It's not complicated to run the bash command in a terminal: sudo sh -c "echo 80 > /sys/class/backlight/rpi_backlight/brightness"
will certainly dim the screen (which is what I want). But how can I sudo
scripts in my python application? (I know that there are several threads talking about this, for example this Using sudo with Python script, but I do not understand how to do it in practice?)
这是我的代码:
#!/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
部分,但是我应该把它放在哪里?
If I run the script right out of box, I get an error with my bash command: bash: /sys/class/backlight/rpi_backlight/brightness: Permission denied
. That's ok, I understand that I am missing the sudo
-part, but where should I put it?
推荐答案
把它放在 shell 前面,就像你交互一样:
Put it in front of the shell just like you do interactively:
subprocess.run(['sudo', 'bash', '-c', bashCommand])
这篇关于sudo 在 subprocess.run 中的什么位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!