using sudo inside jupyter notebook's cell

Viewed 30992

I'm trying to make a tutorial for a platform inside a jupyter notebook

at some point I need to run a linux command inside a cell like this :

!sudo apt-get install blah

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

5 Answers

I want to point another possibility for the case where jupyter is running on localhost: instead of sudo, use pkexec (or for older systems gksu):

!pkexec apt-get install blah

This will ask for the password in a gui solving the problem...

You can pass python variables from a notebook to the shell without importing the os or subprocess modules by using the {varname} syntax (e.g. this cool blog).

If you have defined a password and command variable in python (see Suparshva's answer) then you can run this one-liner:

!echo {password}|sudo -S {command}

The exclamation mark tells jupyter to run it in the shell, the echo command will then get the real password (e.g. 'funkymonkey') from the variable called password and then pipe it into the sudo'd command variable (which is a string that describes a shell command, e.g. 'apt-get update').

If you don't want your password to be stored somewhere, you could write:

from getpass import getpass
!echo {getpass()} | sudo -S {command}

P.S. this also answers Ian Danforth's question

Related