IPython - System Commands



If the statement in the input cell starts with the exclamation symbol (!), it is treated as a system command for underlying operating system. For example, !ls (for linux) and !dir (for windows) displays the contents of current directory

Displaying directories

In [16]: !dir/w
 Volume in drive D is New Volume
 Volume Serial Number is B8D7-1C9E

 Directory of D:\Projects\python\myenv

[.]                    [..]                   .gitignore             [.mypy_cache]          [Include]
[Lib]                  main.py                pyvenv.cfg             RSA_demo_privkey.txt   RSA_demo_pubkey.txt
[Scripts]              [share]                [static]               [templates]            [__pycache__]
               5 File(s)          2,617 bytes
              10 Dir(s)  188,631,117,824 bytes free

In [17]:

Assigning current date to Python Variable

The output of system command can also be assigned to a Python variable as shown below −

In [17]: var = !date

In [18]: var
Out[18]: ['The current date is: 25-12-2025 ', 'Enter the new date: (dd-mm-yy) ']

The variable stores output without colors and splits at newline characters.

It is also possible to combine Python variables or expressions with system command calls. Variable in curly brackets {} can be embedded in command text. Observe the following example −

In [19]: myvar='Interactive Python'

In [20]: !echo "Welcome to {myvar}"
"Welcome to Interactive Python"

Here is another example to understand that prefixing Python variable with $ also achieves the same result.

In [21]: x = 10

In [22]: y = 2

In [23]: !echo "power of {x} raised to {y} is {pow(x,y)}"
"power of 10 raised to 2 is 100"

In [24]: z = pow(x,y)

In [25]: !echo $z
100

In [26]:
Advertisements