I want to do something like the following:
In[1]: name = 'long_name_to_type_every_now_and_then.py'
In[2]: %run name
but this actually tries to run 'name.py'
, which is not what I want to do.
Is there a general way to turn variables into strings?
Something like the following:
In[3]: %run %name%
It seems this is impossible with the built-in
%run
magic function. Your question led me down a rabbit hole, though, and I wanted to see how easy it would be to do something similar. At the end, it seems somewhat pointless to go to all this effort to create another magic function that just usesexecfile()
. Maybe this will be of some use to someone, somewhere.Using this pair of classes, (and given a python script
tester.py
) it's possible to create and use a "macro" variable with the newly created "my_run" magic function like so:Yes, this is a huge and probably wasteful hack. In that vein, I wonder if there's a way to have the name bound to the Macro object be used as the macro's actual name. Will look into that.
IPython expands variables with
$name
, bash-style. This is true for all magics, not just%run
.So you would do:
myscript.py contains:
Via Python's fancy string formatting, you can even put expressions inside
{}
:Use
get_ipython()
to get a reference to the current InteractiveShell, then call themagic()
method:Edit See minrk's answer — that's a much better way to do it.