擅长:python、mysql、java
<p>你能把“sudo”输入子流程吗?请看这个<a href="https://stackoverflow.com/questions/567542">thread</a>。</p>
<p>@Jon Hadley,来自翻译:</p>
<pre><code>>>> import subprocess
>>> p = subprocess.call(['sudo','/usr/bin/env'])
PASSWORD:
[snip]
USER=root
USERNAME=root
SUDO_COMMAND=/usr/bin/env
SUDO_USER=telliott99
SUDO_UID=501
SUDO_GID=20
</code></pre>
<p>从OS X上的终端,我必须在运行脚本时执行sudo:</p>
<pre><code>$ sudo python test.py
</code></pre>
<p>然后这个(在test.py中)给出与前面相同的输出:</p>
<pre><code>import subprocess
p = subprocess.Popen('/usr/bin/env')
</code></pre>
<p>让子流程直接从脚本处理身份验证可能不是一个好主意,因为它隐藏了权限提升。但你可以看看<a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow noreferrer">pexpect</a>和这个<a href="https://stackoverflow.com/questions/250700/is-it-possible-to-communicate-with-a-sub-subprocess-with-subprocess-popen/252100#252100">answer</a>。</p>