Function Call Stack - Print
If you want to print function call stack on log function,then just do following:
import inspect
print(str(inspect.stack()[1][1:4]) + ' ' + "Something to print")
In this example Python code, Stack depth is most important.
Stack depth [1] means that previous calling function frame(or context)
If you use some log api, then you may write like following example:
import inspect
def log_debug(self, msg):
try:
self.logger.debug(str(inspect.stack()[1][1:4]) + ' ' + "Something to print")
Log
Thread
try, except, else, finally
import sockettry:
ip = socket.gethostbyname('daum.net')
except Exception as ex:
print("Exception: type(%s) %s" % (type(ex), ex.args))
print("Exception: %s" % str(ex))
exit()
else:
print("IP Address: %s" % ip)
finally:
print("Once again, IP Address: %s" % ip)
JSON Parser
#!/usr/bin/python3
try:
import json
from pprint import pprint
output = '[{"name": "andrew", "nick": "peter", "location": "Seoul"}]'
json_content = json.loads(output)
pprint(json_content[0])
print("\n My Location: %s" % json_content[0]["location"])
except Exception as ex:
print("My Exception: %s" % str(ex))
TIME, DATE
Example Python code:import time
import datetime
print("Form 1 = %s" % datetime.datetime.now())
print("Form 2 = %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time())))
__file__ and os.path module package
Example Python code:#!/usr/bin/python3
import os
print("__file__: %s" % __file__)
print("realpath: %s" % os.path.realpath(__file__))
print("dirname : %s" % os.path.dirname(os.path.realpath(__file__)))
print("abspath : %s" % os.path.abspath(os.path.dirname(os.path.realpath(__file__))))
Output:
__file__: ./aa.py
realpath: /root/andrew_test/python_example/aa.py
dirname : /root/andrew_test/python_example
abspath : /root/andrew_test/python_example
Popen
You can fork a process and get stream from the pipe of the process.Example Python code:
import subprocess
import shlex
command = "ls -alh"
popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(stdoutdata, stderrdata) = popen.communicate()
print("stdoutdata: %s" % stdoutdata)
print("stderrdata: %s" % stderrdata)
댓글 없음:
댓글 쓰기