Blog of


APyTA_13: Most used modules, Diving into the system

APyTA_13: Most used modules, Diving into the system
Let's talk about the most famous modules.
Theses are not external, they comes as built-in into your python, all you have to do to start playing with them is an import.

pprint (pretty print) is a very handy module to replace the standard print.
Use it when you need a visual feedback on a variable that is a dictionary, or some nested lists.

The module sys (for system) is a module very helpful to prompt python about itself and its mechanics.
We already view the sys.path which return a string list of all the filesystem directory where python will look for when importing.
You can nicely browse all the modules in ram with .modules (example given with pprint):

import sys
import pprint

Another cool feature of this module is the getsizeof function.
Managing HUGE collections of datas ? Big batch loops ? Well then, keep track of what you are really storing.

import sys
sys.getsizeof("a") #41
sys.getsizeof("") #40
sys.getsizeof(None) #16  So None is 2.5 lighter than an empty list, see what I mean ?
sys.getsizeof(False) #24

Sys help also to manipulate its own buffer stream. Python have a three level of buffer : standard In, Out, and Error (coming from linux world).
For us, what is matter is just standard output (error is the same thing), and that we can redirect it:

userInput = #This just open a prompt
print userInput
sys.stdout.write("This is standard output") #See ? Like a print, but without the newline
sys.stderr.write("This is standard error")

sys.stdout = open("F:\PythonCourses\MayaBuffer.txt",'w') #Insert here an already exsisting file
sys.stdout.write("This is standard output") #Nothing is printed in the Maya script editor !

Notice that the file will not be readable instantaneously, but will be flushed when Maya is closed (or if you close it intentionally with .close() ).
We will see above a better way to log your infos. Eventually, know that you also can access to the starting buffer, initialized at python launch.
But now let's have a look at sys.__stdout__ which is a recorded value of default output for printing at python startup.
This helps that a lot because by default it is the output window of Maya ! (Which have better performance, and can isolate your verbosity from usual commands feedback):

sys.__stdout__.write("I am written in Output window, and I like that.")

I use the module time when I need to name my unique files, or when I upload tracking into the Asset Manager.

import time
print time.strftime("%Y-%m-%d") #2012-05-26
print time.strftime("%H:%M:%S") #12:45:47
print time.strftime("%YY-%mM-%dD_%Hh%Mm%Ss") #2012Y-05M-26D_12h46m07s  This is how I format the time personally

The module logging is dedicated to help you keeping trace of your outputs, and I recommend heavily to do that.
CGI Applications crashes. It happens. You need to keep a log of what the user was doing, that is on top of the application. In a file.
It help you a lot, in AGILE development, when frequently users ask you to come to their desk for an "error".
What error ? They do not read it, or they forgot. But the log know.
And you will not have to reproduce the manipulation (which often requires loading a huge file).

import time
#Setuping of the logger:
import logging
logger = logging.getLogger('ToolName')
LogFileFullPath = LOG_FOLDER+"\\"+time.strftime("%YY-%mM-%dD")+'.log' #I record a log in a daily file
logFileHandle = logging.FileHandler(LogFileFullPath)
logFileHandle.setLevel(logging.DEBUG) #This Level could be change in a menu of yours, if the users wants to be in "quiet mode" for example (speed up huge ierations).
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #This is how you setup the prefix of all your lines.
#Example of usage:"This is a normal message") #Use that for classic feedback, resolved variables.
logger.warn("This is a warning message") #Use when something is wrong but the process can continue. Show must go on.
logger.error("This is an ERROR !") #Ok, this is Unexpected context, a non-sense argument. You can not continue. Function will stop and user must know it.
logger.critical("This is the end of the WORLD!!!") #Without the feature in scope (connection to the DB, internet acess for examples), the tool is USELESS. Please contact your administrator and give him a coffee.
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.