2

How to pass % within a string variable to another cell where it is executed?

I define some code as a string and store in a variable where I have a magic function starting with a percentage sign.

I pass this string to another cell where I am trying to execute the code contained in the string.

The percentage sign used in the magic function gives me some problems. The sign is properly displayed in the created string but the execution breaks in the place where the % is.

There is the example:
Cell_1:

string_variable = '%dirs'

Cell_2

print(string_variable)
output:
%dirs

Cell_3

exec(string_variable)

Error: % Invalid Syntax

I tried different ways like /% %% but no one worked.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Chris
  • 767
  • 1
  • 8
  • 23

1 Answers1

2

Python is not going to let you use % in an execute function because it marks the start of a specifier (info here). If you want to use a magic function within a Jupiter notebook you need to import the functions and then call them with your string. There was different ways to do this but below is one way.

from IPython import get_ipython
ipython = get_ipython()

string_variable = '%dirs'

ipython.magic(string_variable)

You should check out this question as well.

BenT
  • 3,172
  • 3
  • 18
  • 38