Python on the command line

Data Processing in Shell

Susan Sun

Data Person

Python basics

Python

  • comes pre-installed on MacOS, Linux
  • needs to be user-install for Windows instructions here
  • can be used with GUI interfaces (e.g Jupyter Notebook, Spyder, PyCharm, etc.)
  • can also be accessed directly via the command line interface
Data Processing in Shell

Using Python documentation

Documentation:

man python
...
-V ,  --version 
    Prints the Python version number of the executable and exits.
python --version
Python 3.5.2
Data Processing in Shell

Using Python documentation

Example: using native Python

which python
/usr/bin/python
Data Processing in Shell

The Python interactive session

To activate a Python interactive session in the terminal:

python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linuxType "help", "copyright", "credits" or 
"license" for more information.
>>>
Data Processing in Shell

The Python interactive session

Inside the interactive session, only use Python syntax:

>>> print('hello world')
hello world

To exit the Python session and return to terminal:

>>> exit()
$
Data Processing in Shell

Python interactive session alternative

Python interactive session:

  • easy to activate, intuitive
  • not good for code reproducibility

Alternative:

  • save Python commands in a Python .py script
  • execute script by calling python + script
Data Processing in Shell

Python script execution on the command line

Method 1

  • Create a .py file using a text editor on the command line (e.g. nano, Vim, Emacs)

Screenshot of the nano text editor in a dark Terminal window

Data Processing in Shell

Python script execution on the command line

Method 2

  • Create a .py file by echo-ing the Python syntax into the hello_world.py file, instantiating the Python file in the same step.
echo "print('hello world')" > hello_world.py

Sanity check file content:

cat hello_world.py
print('hello world')
Data Processing in Shell

Python script execution on the command line

Make sure in the same directory as the .py file:

ls
hello_world.py

Execute .py file by preceding filename with python:

python hello_world.py
hello world
Data Processing in Shell

Let's practice!

Data Processing in Shell

Preparing Video For Download...