【问题标题】:Where to put sudo in subprocess.run?在 subprocess.run 中将 sudo 放在哪里?
【发布时间】: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。

标签: python bash raspbian sudo


【解决方案1】:

我建议只使用 sudo 运行您的 python 脚本...即:sudo myscript.py。这样,它可能运行的任何命令都将具有权限。

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

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

虽然这有点 hacky。我只会以 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']

【讨论】:

    【解决方案2】:

    把它放在 shell 前面,就像你交互做的那样:

    subprocess.run(['sudo', 'bash', '-c', bashCommand])
    

    【讨论】:

    • 谢谢!我的目标是在覆盆子开机时自动启动/运行我的脚本,并且到那时我无法提示 sudo 的密码。如果这解决了我的问题,我会将其标记为答案。
    • 您必须单独配置 sudo 以进行无密码操作
    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多