How to pass a variable to magicrrun function in IPython

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 actually he is trying to run 'name.py' , which I do not want to do.

Is there a general way to turn variables into strings?

Something like the following:

 In[3]: %run %name% 
+71
python ipython ipython-magic
Jan 18 '13 at 23:14
source share
3 answers

IPython extends variables with $name , a bash style. This is true for all magicians, not just %run .

So you would do:

 In [1]: filename = "myscript.py" In [2]: %run $filename ['myscript.py'] 

myscript.py contains:

 import sys print(sys.argv) 

Through Python string formatting, you can even put expressions inside {} :

 In [3]: args = ["arg1", "arg2"] In [4]: %run $filename {args[0]} {args[1][-2:]} ['myscript.py', 'arg1', 'g2'] 
+108
Jan 19 '13 at 4:35 am
source share

Use get_ipython() to get a link to the current InteractiveShell , then call the magic() method:

 In [1]: ipy = get_ipython() In [2]: ipy.magic("run foo.py") ERROR: File `u'foo.py'` not found. 

Edit See minrk answer - this is a much better way to do this.

+10
Jan 18 '13 at 23:51
source share

This seems to be impossible with the built-in magic function %run . However, your question led me to a rabbit hole, and I wanted to see how easy it would be to do something like that. In the end, it seems pointless to go all out to create another magic function that simply uses execfile() . Maybe this will be something useful for someone, somewhere.

 # custom_magics.py from IPython.core.magic import register_line_magic, magics_class, line_magic, Magics @magics_class class StatefulMagics(Magics): def __init__(self, shell, data): super(StatefulMagics, self).__init__(shell) self.namespace = data @line_magic def my_run(self, line): if line[0] != "%": return "Not a variable in namespace" else: filename = self.namespace[line[1:]].split('.')[0] filename += ".py" execfile(filename) return line class Macro(object): def __init__(self, name, value): self.name = name self._value = value ip = get_ipython() magics = StatefulMagics(ip, {name: value}) ip.register_magics(magics) def value(self): return self._value def __repr__(self): return self.name 

Using this couple of classes (and given the python script tester.py ), you can create and use the macro variable with the newly created magic function my_run as follows:

 In [1]: from custom_magics import Macro In [2]: Macro("somename", "tester.py") Out[2]: somename In [3]: %my_run %somename I'm the test file and I'm running! Out[3]: u'%somename' 

Yes, this is a huge and probably wasteful hack. In this vein, I wonder if you can use a name bound to a Macro object as the actual name of the macro. Look at this.

+1
Jan 19 '13 at 0:55
source share



All Articles