Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to magic ´run´ 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 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% 
like image 649
nadapez Avatar asked Jan 18 '13 23:01

nadapez


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 you use %% Timeit in jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.

What is %% capture in Python?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. from __future__ import print_function import sys. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

What is %% Writefile in Jupyter notebook?

%%writefile lets you output code developed in a Notebook to a Python module. The sys library connects a Python program to the system it is running on. The list sys. argv contains the command-line arguments that a program was run with.


2 Answers

IPython expands variables with $name, bash-style. This is true for all magics, 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) 

Via Python's fancy 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'] 
like image 133
minrk Avatar answered Sep 21 '22 07:09

minrk


Use get_ipython() to get a reference 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's answer — that's a much better way to do it.

like image 24
David Wolever Avatar answered Sep 24 '22 07:09

David Wolever