1

嗨,伙计们,我有一个问题。

我正在执行一个需要运行 sudo 命令才能继续的 python 脚本。这是命令:

sudo /etc/init.d/test restart

问题是,无论我如何执行它,它只会运行 sudo 和 /etc/init.d/test 并返回:

sudo: /etc/init.d/test: command not found

问题似乎是重新启动没有与命令一起发送。

这些是我尝试运行命令的方式:

尝试 1 使用操作系统

os.system('sudo /etc/init.d/test restart')

尝试 2 使用子进程

x = subprocess.Popen(['sudo','/etc/init.d/test','restart'])
x.communicate()

尝试 3 再次使用子进程

x = subprocess.Popen(['sudo','/etc/init.d/test restart'])
x.communicate()

这实际上返回:

sudo: /etc/init.d/test restart: command not found

这没有任何意义,因为如果我直接在系统上执行命令,它就可以工作。
关于我如何做到这一点的任何想法?

4

2 回答 2

3
#!/usr/bin/env python
import subprocess,getpass
password = getpass.getpass()
#proc = subprocess.Popen(
#  ['sudo','-p','','-S','/etc/init.d/test','restart'],
#   stdin=subprocess.PIPE)
proc = subprocess.Popen(
    ['sudo','-p','','-S','echo','restart'],
    stdin=subprocess.PIPE)
proc.stdin.write(password+'\n')
proc.stdin.close()
proc.wait()
于 2013-04-03T13:15:54.943 回答
0

如果你得到这个:

sudo: /etc/init.d/test: command not found

它表示 /etc/init.d/test 不存在。从命令行自己尝试一下:

> sudo blarg whatever whatever
sudo: blarg: command not found

因此,只需确保您尝试执行的命令确实存在:

ls -l /etc/init.d/test

如果你仍然有问题,然后尝试通过首先让它执行'sudo whoami'来简化事情——一旦你开始工作,把它改成你的“真实”命令。

于 2013-04-03T13:38:07.347 回答