Archive

Posts Tagged ‘shell’

[Windows] clear screen in the Python shell

February 22, 2022 Leave a comment

Problem

Under Linux, when using the Python shell, it’s very easy to clear the screen. Just press Ctrl+L. But what about Windows? Ctrl+L doesn’t work there :( Is there a painless way to clear the screen under Windows?

Solution

We’ll create a function called cls() that will clear the screen. Usage example:

C:\> python
>>> a = 5
>>> cls()

For this, create a file called .pystartup (the name doesn’t matter). Add the following function to it:

def cls():
    """
    clear screen for Windows
    """
    import os
    cmd = 'cls' if os.name == 'nt' else 'clear'
    os.system(cmd)

Create a new environment variable called PYTHONSTARTUP and assign the path of .pystartup to it. Example:

PYTHONSTARTUP=C:\opt\.pystartup

Open a new terminal. Now, if you start the Python shell, it’ll read the content of the file above. Thus, the function cls() will be available in all your Python shell sessions.

It also works under Linux. You can add more utility functions to .pystartup (however, I think it’s a good idea to keep it minimal).

Categories: python Tags: , , , , ,

Python from command line

September 18, 2013 Leave a comment

Problem
You want to calculate something with Python quickly, from the command line. You might even want to use Python in a bash script to produce some result.

Solution

$ python -c "print(2*3)"
6

Storing the result in a variable:

$ X=`python -c "print(2*3)"`
$ echo $X
6

Thanks to Tajti A. for the tip.

Update (20170803)
You can also pass a bash variable to the embedded Python:

VAL="cat dog cat"
NEW=`python3 -c "print('$VAL'.replace('dog', 'wolf'))"`
echo $NEW

Output: “cat wolf cat”.

Categories: python Tags: , , ,

call python in a shell script

March 5, 2012 Leave a comment

Problem
Floating point arithmetic in bash is problematic, expr supports integers only for instance.

Solution
Not an optimal solution but it works:

$ python -c "print 5.5*3"
16.5

$ num=`python -c "print 5.5*3"`
$ echo $num
16.5
Categories: python Tags: ,

IPython, an enhanced Python shell

March 19, 2011 Leave a comment

IPython is an interactive shell for the Python programming language that offers enhanced introspection, additional shell syntax, syntax highlighting, tab completion and rich history. It is a component of the SciPy package.” (source)

Links:

In the book Python for Unix and Linux System Administration, there is a long chapter (Ch. 2) dedicated to IPython!

Installation and usage
Install it via apt-get:

sudo apt-get install ipython

I made the alias “ip” for the command “ipython”. Note that there is a command “ip” for manipulating routing and tunnels that the alias will hide, but it’s not likely I’ll ever use that command.

alias ip='ipython'

The config file of IPython is located at ~/.ipython/ipy_user_conf.py.

Categories: python Tags: , ,