Thursday, July 12, 2018

Python Interpreter


Introduction
------------

- interpreter directly executes your code/instruction w/o compiling
- operates like a Unix shell:
    a. when called with standard input connected to a tty device,
       it reads and executes commands interactively
    b. when called with a file name argument or with a file as
       standard input, it reads and executes a script from that file

Location
--------

*nix systems
/usr/local/bin/python3X
windows systems
C:\Python3X

Setting Python Path
-------------------

Windows
1. My Computer > right click > advanced settings
2. edit system variables
3. PYTHONPATH = C:\path\to\python\installation\folder
4. PATH: add %PYTHONPATH%

Navigation and Control
----------------------

- commands can be executed inside the interpreter (interactive mode)
- python scripts can also be called outstide the interpreter

calling/starting
# brings you to sub shell/interpreter
python

# executes a command as if you're inside the interpreter
python -c "print('hello world')"
python -c "import os; os.mkdir(r'c:\users\john\desktop\test')"

# invokes a python module
python -m SimpleHTTPServer

# runs a python script
python adduser.py

# runs a script and enter interactive mode afterwards
python -i create_folder.py
exiting
# windows
CTRL + Z
exit()
quit()

# *nix
CTRL + D
exit()
quit()

Features
--------

- line-editing features aren't very sophisticated
- some may have GNU readline library w/c adds history features
- to check if interpreter supports command line editing, press CTRL + P
    > w/ beep: supported
    > no beep: not supported (you may only use backspace to remove characters)
- some command line editing features:
    a. line editing - CTRL + A/E moves cursor to beginning/end of line
    b. history subsitution - UP/DOWN arrows to navigate history, CTRL + R for reverse search, etc..
    c. key-bindings - similar to aliases

Argument Passing
----------------

- if `python -c COMMAND` is used, python stores `-c` inside `sys.argv[0]`
- if `python -m MODULE` is used, python stores the full path to module inside `sys.argv[0]`
- if `python -` is used (standard input), python stores `-` inside `sys.argv[0]`
- if `python` is used (no script or argument given), `sys.argv[0]` is an empty string
- options found after `-c COMMAND` or `-m MODULE` is not consumed by Python interpreter's option
  processing but left in `sys.argv` for the command or module to handle

demo
bash$ python -c "import sys; print(sys.argv[0])"
-c
bash$
converts arguments to a list
$ python3 -c "import sys;print(sys.argv[1:])" a b c d
['a', 'b', 'c', 'd']
$

Interactive Mode
----------------

- commands are read from tty (/dev/tty)
- to enter into interactive mode, type `python`
- prompt is denoted by `>>>`
- upon entering interactive mode, python version is printed

demo
$ python3.3
Python 3.3 (default, Sep 24 2012, 09:25:04)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")  # multi-line construct denoted by `...`
...
Be careful not to fall off!


Error Handling
--------------

- When an error occurs, the interpreter prints an error message and a stack
  trace
    > In interactive mode, it then returns to the primary prompt
    > when input came from a file, it exits with a nonzero exit status after
      printing the stack trace
- Exceptions handled by `except` clause in a `try` statement are not errors
- Errors are written to standard error stream
- Normal output are written to standard output
- Typing interrupt character (CTRL +C) cancels input and return to secondary
prompt

demo
>>> print('hello')
KeyboardInterrupt  # this can be handled via `try` statement
>>>

Executable Python Scripts
-------------------------

*nix systems
You must add any of the following lines as the first line of
your script.

#!/usr/bin/env python
#!/usr/bin/python

Then followed by a `chmod +x` on the file.

Note that those lines must use a Unix-style ending ('\n') and not a Windows-style
ending ('\r\n').

If those lines are not present or an executable bit was not added,
you may run the script by:

python script.py
windows systems
Windows has no concept of executable bit. You may just save the file as filename.py
and windows will treat it as filename.exe. So double-clicking that file will execute it.
You will notice a black screen appearing fast when the script is executing.

To remove that black screen, save the file as filename.pyw. Naming it that way will also
supress output when you run the script in the terminal.
What interpreter to use?
#!/usr/bin/env vs #!/usr/bin/python
 
- python path varies from one machine to another
- using `/usr/bin/python` may not work on another machine if python is installed
  on different path
- `/usr/bin/env` will automatically find your python path regardless on what
  machine you are
- `/usr/bin/env` is standard on all machines; if that is not present, your machine is
  broken

source:

Source Code Encoding
--------------------

By default Python source files uses UTF-8 encoding (mapping of characters into
bytes). You're editor must be able to read UTF-8 encoded texts to display the
source file properly.

To specify a different encoding for your source file, put this line after `#!`:

  # -*- coding: encoding -*-

Example:

  #!/usr/bin/env python
  # -*- coding: cp-1252 -*-

List of possible encodings can be found on: https://docs.python.org/3.3/library/codecs.html#module-codecs

Interactive Startup File
------------------------

You can define a file containing commands to execute everytime you enter
interactive mode. That file is the Python startup script and is set to
environment variable "PYTHONSTARTUP". It is only read during interactive mode
and not when you run a python script via `python script.py`.

To define on *Nix systems
1. Edit .bash_profile

2. Add the following line:
     export PYTHONSTARTUP=$HOME/.pythonrc.py

3. Create that file and put any commands you want to execute
   during startup.
     import os
     import socket

3. Logout from current session

4. Login again and enter iteractive mode.

5. Notice you don't need to import `os` and `socket` modules because
   the startup file already did that for you.
   >>> os.getcwd()
   '/home/john'
   >>>
To define on Windows systems
Similar way in defining like in *Nix. The only difference is the way on
how to add the environment variable which is done via "Advanced system settings"
































Customization Modules
---------------------

Python has the ability to import files every python invocation.

`sitecustomize.py`
`usercustomize.py`

Those files are similar to PYTHONSTARTUP but this time they read not only when
you start interactive mode but also when you run a python script via `python`
command unless you use `-S`.

To create those files, determine first on what location you should put them.

>>> import site
>>>
>>> site.getusersitepackages()
'/root/.local/lib/python2.7/site-packages'
>>>
>>> site.getsitepackages()
>>> ['/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages', '/usr/lib/site-python']

Then create the file(s) of your choice.

$ cat << EOF > /root/.local/lib/python2.7/site-packages/usercustomize.py  # create usercustomize first
> #!/usr/bin/env python
> import os
> os.mkdir('/tmp/python-startup-dir/')
> EOF
$
$ ll -d /tmp/python-startup-dir/
ls: cannot access /tmp/python-startup-dir/: No such file or directory
$
$ python hello.py
hello world
$
$ ll -d /tmp/python-startup-dir/
drwxr-xr-x. 2 root root 6 Jul 21 21:03 /tmp/python-startup-dir/  # directory is created by usercustomize
$ rmdir /tmp/python-startup-dir/
$
$ cat << EOF > /usr/lib64/python2.7/site-packages/sitecustomize.py  # let's create sitecustomize with same content
> #!/usr/bin/env python
> import os
> os.mkdir('/tmp/python-startup-dir/')
> EOF
$
$ python -c "print('hello world')"                   # running another python invocation imports sitecustomize
'import usercustomize' failed; use -v for traceback  # first then tries importing usercustomize afterwards w/c
hello world                                          # failed because sitecustomize already created the directory
$

More on Interactive Mode
------------------------

Here is a demo on what looks like when you're inside interactive mode.

>>>           # this is the first comment
>>> spam = 1  # and this is the second comment
>>>           # ... and now a third!
>>>
>>> text = "# This is not a comment because it's inside quotes."
>>>
>>> def test():
...   pass
...           # blank line is required to end a multi-line construct
>>>

Sample Python program: Fibonacci series
---------------------------------------

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8

cycle
print(b)
a
b
b < 10
init

0
1
YES
1
1
1
1
YES
2
1
1
2
YES
3
2
2
3
YES
4
3
3
5
YES
5
5
5
8
YES
6
8
8
13
NO

The first line contains a multiple assignment: the variables a and b
simultaneously get the new values 0 and 1. On the last line this is used again,
demonstrating that the expressions on the right-hand side are all evaluated
first before any of the assignments take place. The right-hand side expressions
are evaluated from the left to the right.

The while loop executes as long as the condition (here: b < 10) remains true. In
Python, like in C, any non-zero integer value is true; zero is false. The
condition may also be a string or list value, in fact any sequence; anything
with a non-zero length is true, empty sequences are false. The test used in the
example is a simple comparison. The standard comparison operators are written
the same as in C: < (less than), > (greater than), == (equal to), <= (less than
or equal to), >= (greater than or equal to) and != (not equal to).

The body of the loop is indented: indentation is Python’s way of grouping
statements. At the interactive prompt, you have to type a tab or space(s) for
each indented line. In practice you will prepare more complicated input for
Python with a text editor; all decent text editors have an auto-indent facility.
When a compound statement is entered interactively, it must be followed by a
blank line to indicate completion (since the parser cannot guess when you have
typed the last line). Note that each line within a basic block must be indented
by the same amount.

The print() function writes the value of the argument(s) it is given. It differs
from just writing the expression you want to write (as we did earlier in the
calculator examples) in the way it handles multiple arguments, floating point
quantities, and strings. Strings are printed without quotes, and a space is
inserted between items, so you can format things nicely, like this:

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

The keyword argument end can be used to avoid the newline after the output, or
end the output with a different
string:

>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

No comments:

Post a Comment