Update: I checked all the methods, all of them are working.
1:
Request password using getpass module
which essentially hides input by user and then run sudo command in python.
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
NOTE for above methods:
The field where you enter the password may not appear in the ipython
notebook. It appears in the terminal window on a mac, and I imagine it
will appear in a command shell on a PC. Even the result details would appear in the terminal.
3:
You can store your password in mypasswordfile
file and just type in cell :
!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S is important here
I would prefer this method if I want to view output of the command in jupyter notebook itself.
References:
-
Requesting password in IPython notebook
-
https://docs.python.org/3.1/library/getpass.html
- Using sudo with Python script