在 subprocess.run 中哪里放置 sudo ?

Hau*_* TM 5 python bash sudo raspbian

我正在尝试从 python 应用程序调用 bash 命令,以更改触摸屏上的背景光。python 应用程序将在我的 Raspberry Pi (Rasbian/stretch) 上运行。

在终端中运行 bash 命令并不复杂:sudo sh -c "echo 80 > /sys/class/backlight/rpi_backlight/brightness"肯定会使屏幕变暗(这就是我想要的)。但是如何sudo在 python 应用程序中编写脚本呢?(我知道有几个线程正在讨论这个问题,例如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
Run Code Online (Sandbox Code Playgroud)

如果我直接运行脚本,我的 bash 命令会出现错误:bash: /sys/class/backlight/rpi_backlight/brightness: Permission denied。没关系,我知道我缺少sudo- 部分,但我应该把它放在哪里?

tha*_*guy 7

将其放在 shell 前面,就像交互式操作一样:

subprocess.run(['sudo', 'bash', '-c', bashCommand])
Run Code Online (Sandbox Code Playgroud)


m.a*_*cat 7

我建议只使用 sudo... ie: 运行你的 python 脚本sudo myscript.py。这样,它可能运行的任何命令都已经拥有特权。

您可以使用 that_other_guy 的答案,但您的脚本仍会提示您输入密码(至少在我的情况下是这样)。因此这个答案不太好。

如果你真的想自动化它,但你不想以 root 身份运行它......你需要使用 that_other_guys 的答案,但也需要回显你的密码,如下所示

不过这有点老套了。我只需使用 root 权限运行 python 脚本本身。

但是,如果您确实不想以 root 身份运行它,那么您可以这样做:

>>> from subprocess import run, PIPE
>>> cmd = "echo mypassword | sudo -S ls"
>>> out = run(cmd, shell=True, stdout=PIPE)
>>> output = [i for i in out.stdout.decode().split('\n') if i]
>>> output
['build', 'dist', '__init__.py', 'palindrome', 'palindrome.egg-info', 'LICENSE', 'README.md', 'setup.py']
Run Code Online (Sandbox Code Playgroud)