更新: 我检查了所有方法,所有方法都有效。
1:
请求密码,
getpassmodule该密码实际上会隐藏用户的输入,然后在python中运行sudo命令。
import getpass import os password = getpass.getpass() command = "sudo -S apt-get update" #can be any command but don't forget -S as it enables input from stdin os.system('echo %s | %s' % (password, command))2:
import getpass import os password = getpass.getpass() command = "sudo -S apt-get update" # can be any command but don't forget -S as it enables input from stdin os.popen(command, 'w').write(password+'n') # newline char is important otherwise prompt will wait for you to manually perform newline
上述方法的注意事项:
您输入密码的字段可能不会出现在ipython笔记本中。它出现在Mac的终端窗口中,我想它会出现在PC的命令外壳中。甚至结果详细信息也将出现在终端中。
3:
您可以将密码存储在
mypasswordfile文件中,只需输入cell即可:
!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S isimportant here
如果我想在jupyter notebook本身中查看命令的输出,我会更喜欢这种方法。



