Skip to content

Commit f5f385f

Browse files
author
Jonathan Rocher
committed
Adding an example for subprocess, another one for logging and one last for context managers.
1 parent b22b7cb commit f5f385f

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

example_context.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
""" Simplest possible example of a context manager
2+
"""
3+
4+
class MyContext(object):
5+
def __enter__(self):
6+
print "I entered"
7+
return self
8+
9+
def __exit__(self, type, value, tb):
10+
print "Before exiting important things to do..."
11+
print("Information about potential exception: \n"
12+
"type=%s, value=%s, trace=%s" % (type, value, tb))
13+
14+
if __name__ == "__main__":
15+
with MyContext() as c:
16+
print "I am doing things"
17+
raise RuntimeError("Something bad happened")
18+
19+
print "Continuing normal execution"

example_logging.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
import logging
3+
from logging.handlers import RotatingFileHandler
4+
5+
logger=logging.getLogger()
6+
7+
log_file = "log.txt"
8+
file_handler = RotatingFileHandler(log_file, maxBytes=1024 ** 2,
9+
backupCount=3)
10+
formatter = logging.Formatter("%(levelname)s - %(asctime)s - %(name)s "
11+
"- %(message)s")
12+
file_handler.setFormatter(formatter)
13+
logger.setLevel(logging.DEBUG)
14+
logger.addHandler(file_handler)
15+
16+
logger.debug("test")

example_subprocess.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from subprocess import Popen
2+
import sys
3+
4+
print "Starting..."
5+
# sleep for 10 seconds
6+
p = Popen(['sleep','10'])
7+
# continue on with processing
8+
print "Continuing",
9+
k=0
10+
while p.poll() is None:
11+
k += 1
12+
if (k % 100000) == 0:
13+
print k//100000,
14+
sys.stdout.flush()
15+
print
16+
print "Done", p.returncode

0 commit comments

Comments
 (0)