Skip to content Skip to sidebar Skip to footer

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 = 'littl

Solution 1:

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}

Solution 2:

would you try something like this:

sp_name = 'littleGuy'#the variablesp_query = "DisplayName eq "+sp_name 

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

Solution 3:

The issue can be also resolved using something like below

sp_name = 'littleGuy'#the variable
sp_details = !az ad app list --filter"DisplayName eq '{sp_name}'"

Post a Comment for "Passing Ipython Variables As String Arguments To Shell Command"