因此,我试图使用子进程从 python 脚本中获取一个以超级用户身份运行的进程。在 ipython shell 中类似
proc = subprocess.Popen('sudo apach2ctl restart',
shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
工作正常,但是一旦我将其粘贴到脚本中,我就开始得到:sudo: apach2ctl: command not found
.
我猜这是由于 sudo 处理 ubuntu 环境的方式造成的。 (我也尝试过sudo -E apche2ctl restart
and sudo env path=$PATH apache2ctl restart
无济于事)
所以我的问题基本上是,如果我想跑步apache2ctl restart
作为超级用户,在需要时提示用户输入超级用户密码,我应该如何执行此操作?我无意在脚本中存储密码。
Edit:
我尝试将命令作为字符串传递并标记为列表。在 python 解释器中,使用字符串我将正确获得密码提示(仍然无法像我原来的问题那样在 python 脚本中工作),列表仅提供 sudo 的帮助屏幕。
Edit 2:
所以我收集到的是,虽然当 shell=True 时 Popen 将像字符串一样处理某些命令,但它需要
proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])
没有 'shell=True' 来让 sudo 工作。
Thanks!