Top Ten Magic Commands of Python

Magic commands are enhancements to regular python code, usually prefixed with "%" characters. These commands are provided by the IPython kernel, and are basically added to solve common problems, and also provide some shortcuts for the code.

There are two types of magic commands:% prefix and %% prefix. The% prefix indicates that the command operates on a line of code, while the %% prefix allows the command to operate on the entire computing unit.

The following are some magic commands and their implementations, all executed in JupyterNotebook.

1. Run external files

When trying to run some code snippets in JupyterNotebook, I hope to run an external code file located in a certain directory. %Run allows to run any external python file from Jupyter Notebook.

img

The above file myCode.py contains a simple script that outputs the above statement.

img

If you specify a file name that includes the path of the %run command, it will execute the file.

Note: %Run also allows execution of external Jupyter Notebook.

2. Code execution time

Ever wondered how long it will take to run the computing unit? The Time magic command allows tracking the total execution of the computing unit. Since the entire calculation unit will be processed here, %% is used as the prefix before the time keyword.

img

The calculation unit above includes a for loop with random calculations. %%time helps to get the time required to run the for loop.

3. Copy the content to an external file

Most of the time, it is necessary to add content directly from JupyterNotebook to a python script or text file. You can export the unit content directly by adding the writefile command before the code, instead of copying everything and creating a new file.

Note that the double% in front of the command means that the entire contents of the unit will be exported.

img

Because this file has been created with some content, it shows "OverwritemyCode.py". Specify that it will overwrite the original content with the content shown in the image above.

4. List all variables

This magic command shows all the variables used in the entire notebook. The following are 3 variables-2 strings and 1 integer. If you run %who, it will list all 3 variables defined.

a = "hello"
b = "Good Morning"
c = 1

img

The above code shows all variables, regardless of their data types.

img

In order to display a specific data type variable, the data type needs to be passed after the magic command. The above code displays all string data type variables as their output.

5. Share variables between notebooks

This magic command allows any variables to be shared between different Jupyter Notebooks. You need to use magic commands to pass primitive variables. To get this variable, you need to pass the same command with the "-r" parameter.

This is what the first notebook looks like:

img

The code required to obtain this data is written in another notebook.

img

This is probably the easiest way to share data of any data type between different notebooks.

6. Display the content of external files

It is usually necessary to copy a few lines of code from an external file into the code. %Pycat allows to display the contents of any file in any directory, instead of going through a lengthy process to get the file and open it for copying.

img

It displays all the contents of the external file as its output. As far as its application is concerned, it can be seen as the reverse of %writefile.

7. Execute html script

%% html allows writing html code in the unit. Now, the unit will act as an html editor, outputting the html of the unit.

The following code contains a simple table created in html. You can notice that the html output shows the expected table.

%%html
<html>
<body>
<table>
        <tr>
            <th>Name</th>
            <th>Country</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>Sid</td>
            <td>India</td>
            <td>22</td>
        </tr>
        <tr>
            <td>Dave</td>
            <td>UK</td>
            <td>28</td>
        </tr>
</table>
</body>
</html>

img

Tip: You can use the %%jsmagic command similar to the HTML magic command to run Javascript code in the unit.

8. Display Matplotlib graphs

The %matplotlibinline magic command is the most popular command. This command allows Jupyternotebook to display matplotlib graphics in the notebook. This command activates matplotlib's interactive support for Jupyter Notebook.

import random
import matplotlib.pyplot as plt
%matplotlib inline

Some libraries that need to explain the function of commands have been imported.

Now two random lists will be created to draw the graph:

a = []
b = []
for i in range(10):
    a.append(random.randint(0,10))
    b.append(random.randint(0,10))

Now you will draw a scatter plot of the data.

plt.scatter(a,b)

img

The %matplotlibinlin magic command allows to visualize graphs in Jupyter Notebook.

9. Set environment variables

This magic command can do three things-list all environment variables, get the value of a specific environment variable, and set a value for a variable.

img

%Env without parameters will list all environment variables.

img

%Env with a single parameter will return the value of the specified parameter.

%env variable value: the variable will set the value of the specified variable name.

10. Details of the object

%pinfo provides detailed information about the objects passed with it. It is similar to the function of an object.

In the following code snippet, a simple string a is passed, and %pinfo is used to obtain its detailed information.

a = "The World Makes Sense!"
%pinfo a

img

In the above output, %pinfo provides all the information about the string object.

You can use the %lsmagic command to find a list of all magic commands.

img

Guess you like

Origin blog.csdn.net/weixin_44322234/article/details/106282773