我想与子进程终端交互并发送密码,但我注意到如果某些程序调用 getpass(prompt)
( http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/getpass.html )
这意味着我无法与sudo
和ssh
交互,那么如何解决这个问题呢?谢谢。
例子如下:
process = subprocess.Popen(['sudo', 'apt', 'update'],
bufsize=0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
while True:
# prefix '>>' in parent process
# but we could see the stdout without prefix, that means read() never return
# the subprocess just ignored the redirect of stdout
print('>>', process.stdout.read())
time.sleep(1)
最佳答案
你的问题不清楚,不过我会尽量回答
如果要发送密码,可以使用communicate()方法
关于 communicate() 的更多信息在这里 Multiple inputs and outputs in python subprocess communicate
所以你的代码应该是这样的
from subprocess import Popen,PIPE
proc = Popen(['sudo', 'apt', 'update'],
bufsize=0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
testoutput=proc.communicate(input='your password')[0] # This will enter the password and wait for the process to exit
print ''.join(testoutput)
关于输入密码时,Python 子进程模块无法重定向标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990982/