Skip to content

Commit f1f65b9

Browse files
committed
Copy relevant source code samples
1 parent 389708c commit f1f65b9

File tree

95 files changed

+55057
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+55057
-0
lines changed

source-code/cmd/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Cmd
2+
Standard Python library framework to facilitate writing command line
3+
driven interpreters.
4+
5+
## What is it?
6+
1. `simple.py`: a very simmple example that keeps track of a list of
7+
friends. A friend is added by saying `hi` to her, and is removed by
8+
saying `bye` to her. You can't say `hi` to someone who is your friend
9+
already, and you can't say `bye` to someone who isn't your friend.
10+
`show_friends` lists the current friends. `quit` exits the
11+
application. Note that `help` and tab completion are automatically
12+
provided.

source-code/cmd/simple.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
3+
import cmd
4+
5+
6+
class HelloShell(cmd.Cmd):
7+
intro = 'Welcome to the HelloShell, type ? to see a list of commands'
8+
prompt = 'hello> '
9+
10+
def __init__(self):
11+
'''constructor'''
12+
super().__init__()
13+
self._people = set()
14+
15+
def do_hi(self, args):
16+
'''say hi'''
17+
if args in self._people:
18+
print('already said hi to {0}'.format(args))
19+
else:
20+
self._people.add(args)
21+
print('hi {0}'.format(args))
22+
23+
def do_bye(self, args):
24+
'''say bye'''
25+
if args in self._people:
26+
self._people.remove(args)
27+
print('bye {0}'.format(args))
28+
else:
29+
print('never said hi to {0}'.format(args))
30+
31+
def do_show_friends(self, args):
32+
'''show all current friends'''
33+
if self._people:
34+
print('all friends: {0}'.format(', '.join(self._people)))
35+
else:
36+
print('lonely, no friends')
37+
38+
def do_quit(self, args):
39+
'''quit the HelloShell'''
40+
print('thanks for coming by')
41+
return True
42+
43+
if __name__ == '__main__':
44+
HelloShell().cmdloop()

source-code/code-evaluation/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
EvaluateCode
2+
============
3+
4+
Python allows executino of Python source code at runtime. Although this
5+
is a powerful feature, it should be used with extreme care, since it can
6+
give rise to serious security issues.
7+
8+
What is it?
9+
-----------
10+
1. `evaluate.py`: short example that reads a code fragment, evaluates it,
11+
and prints all values of variables defined in that code fragment.
12+
Only variables of type `int`, '`float`, `str`, `bool` and `list` will
13+
be printed.`
14+
1. `source.py`: sample code to evaluate using `evaluate.py`.
15+
1. `nasty.py`: sample code to illustrate that `exec` can be harmful; will
16+
delete `my_precious.txt`, which should be copied from `my_precious.orig`;
17+
to be evaluated by `evaluate.py`.
18+
1. `my_precious.orig`: file to copy to `my_precious.txt`.
19+
1. `fib.py`: definition of Fibonacci function.
20+
1. `fac.py`: definition of the recursive permutation function.
21+
1. `fac_iter.py`: definition of the iterative permutation function.
22+
1. `exec.py`: script that illustrates various uses of `exec`.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/usr/bin/env python
2+
3+
if __name__ == '__main__':
4+
from argparse import ArgumentParser
5+
arg_parser = ArgumentParser(description='Read and exectue Ptyhon '
6+
'source code in a local '
7+
'environment')
8+
arg_parser.add_argument('file', help='Python file to parse')
9+
options = arg_parser.parse_args()
10+
with open(options.file, 'r') as source_file:
11+
source = ''.join(source_file.readlines())
12+
globals = {}
13+
locals = {}
14+
exec(source, globals, locals)
15+
for obj, val in locals.items():
16+
if type(val) in [int, float, str, bool]:
17+
print('{0} = {1}'.format(obj, str(val)))

source-code/code-evaluation/exec.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#!/usr/bin/env python
2+
3+
# place definition in global scope
4+
with open('fib.py', 'r') as func_file:
5+
func_str = ''.join(func_file.readlines())
6+
exec(func_str)
7+
n = 5
8+
print('fib({0:d}) = {1:d}'.format(n, fib(n)))
9+
10+
# place definitions in private scope, no problem for non-recursive functions
11+
with open('fac_iter.py', 'r') as func_file:
12+
func_str = ''.join(func_file.readlines())
13+
priv_globals = {}
14+
priv_locals = {}
15+
exec(func_str, priv_globals, priv_locals)
16+
print('fac({0:d}) = {1:d}'.format(n, priv_locals['fac_iter'](n)))
17+
18+
# place definitions in private scope, problem for recursive functions
19+
with open('fac.py', 'r') as func_file:
20+
func_str = ''.join(func_file.readlines())
21+
priv_globals = {}
22+
priv_locals = {}
23+
exec(func_str, priv_globals, priv_locals)
24+
try:
25+
result = eval('fac({0})'.format(n), priv_globals, priv_locals)
26+
print('fac({0:d}) = {1:d}'.format(n, result))
27+
except NameError as error:
28+
print('Exception: {0}'.format(str(error)))
29+
30+
# when evaluating within string, no problem
31+
exec('{0}\nresult = fac({1:d})'.format(func_str, 5))
32+
print('fac({0:d}) = {1:d}'.format(n, result))

source-code/code-evaluation/fac.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def fac(n):
2+
if n < 2:
3+
return 1
4+
else:
5+
return n*fac(n-1)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def fac_iter(n):
2+
result = 1
3+
for i in range(2, n + 1):
4+
result *= i
5+
return result

source-code/code-evaluation/fib.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def fib(n):
2+
if n == 0 or n == 1:
3+
return 1
4+
else:
5+
return fib(n-1) + fib(n-2)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This is very precious data.

source-code/code-evaluation/nasty.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from pathlib import Path
2+
3+
path = Path.cwd()
4+
path /= 'my_precious.txt'
5+
print('Now deleting your precious data...')
6+
path.unlink()

0 commit comments

Comments
 (0)