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%
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.
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.
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.
%%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.
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With