Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Ipython variables as string arguments to shell command

How do I execute a shell command from Ipython/Jupyter notebook passing the value of a python string variable as a string in the bash argument like in this example:

sp_name = 'littleGuy' #the variable

sp_details = !az ad app list --filter "DisplayName eq '$sp_name'" #the shell command

I've tried using $sp_name alone, ${sp_name}, {sp_name} etc as outlined in this related question, but none have worked.

The kicker here is the variable name needs to be quoted as a string in the shell command.

EDIT1:

@manu190466. I was judging from the string output that your solution worked. It appears for some reason it does not in practice. I wonder if az ad app list URL encodes the query or something...?

Thoughts?

enter image description here

like image 657
SeaDude Avatar asked May 05 '20 04:05

SeaDude


People also ask

What does %% do in Jupyter notebook?

Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.

How do I set an environment variable in IPython?

Environment variables environ directly, you may like to use the magic %env command. With no arguments, this displays all environment variables and values. To get the value of a specific variable, use %env var . To set the value of a specific variable, use %env foo bar , %env foo=bar .

What is IPython shell?

IPython (Interactive Python) is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.


1 Answers

The main problem you encounters seems to come from the quotes needed in your string. You can keep the quotes in your string by using a format instruction and a raw string.

Use a 'r' before the whole string to indicate it is to be read as raw string, ie: special caracters have to not be interpreted. A raw string is not strictly required in your case because the string constructor of python is able to keep single quotes in a double quotes declaration but I think it's a good habit to use raw string declarators when there are non alphanumerics in it.

There are at least two way to format strings :

Older method herited from ancient langages with % symbols:

sp_name = 'littleGuy' #the variable
sp_query = r"DisplayName eq '%s'"%(sp_name) 

sp_details = !az ad app list --filter {sp_query}

Newer method with {} symbols and the format() method :

sp_name = 'littleGuy' #the variable
sp_query = r"DisplayName eq '{}'".format(sp_name) 

sp_details = !az ad app list --filter {sp_query}
like image 85
manu190466 Avatar answered Oct 06 '22 14:10

manu190466