Page History
Content
Table of Contents |
---|
Parsing of input parameters
Parsing "on knees"
Code Block |
---|
Wiki Markup |
h1. Content {toc} h1. Parsing of input parameters h3. Parsing "on knees" {code} import sys import os def get_input_parameters() : nargs = len(sys.argv) print 'sys.argv[0]: ', sys.argv[0] print 'nargs: ', nargs # Then do something with arguments... {code} h3. Use OptionParser {code} |
Use OptionParser
Code Block |
---|
from optparse import OptionParser def input_option_parser() : def_fname = 'spec-xppi0412-r0060-20120507-125420.198726277.txt' def_cols = 100 parser = OptionParser(description='Process optional input parameters.', usage = "usage: %prog [options]") parser.add_option('-f', '--fname', dest='fname', default=def_fname, action='store', type='string', help='input file name') parser.add_option('-c', '--cols', dest='cols', default=def_cols, action='store', type='int', help='number of columns in the image array') parser.add_option('-v', dest='verbose', action='store_true', help='set flag to print more details', default=True) parser.add_option('-q', dest='verbose', action='store_false', help='set flag to print less details') (opts, args) = parser.parse_args() print 'opts:',opts print 'args:',args return (opts, args) |
Manipulation with directories and files
Access to files in the derectory
Code Block |
---|
{code}
h1. Manipulation with directories and files
h3. Access to files in the derectory
{code}
def getListOfFilesInDir(dirname) :
return os.listdir(dirname)
def printListOfFilesInDir(dirname) :
print 'List of files in the dir.', dirname
for name in os.listdir(dirname) :
print name
print '\n'
|
Parsing the pathname
Code Block |
---|
{code} h3. Parsing the pathname {code} root, ext = os.path.splitext(path) # i.e. path='root-part.tail-part' basename = os.path.basename(path) dirname = os.path.dirname(path) lexist = os.path.lexists(path) isfile = os.path.isfile(path) isdir = os.path.isdir(path) head, tail= os.path.split(path) # i.e. path='head-part/tail-part' ... {code} [ |
http://docs.python.org/library/os.path.html
...
Useful string parsing options
http://docs.python.org/library/string.html
Code Block |
---|
} string.rsplit(str, sep, maxsplit) string.capitalize(word) string.lower(s) start = string.find(symbolic_string, pattern) pattern_length = len(pattern) {code} [ |
http://docs.python.org/library/parser.html
...
?
...
Or
...
use
...
more
...
shorter
...
methods
...
for
...
str
...
object:
...
http://docs.python.org/library/stdtypes.html
...
,
...
for
...
example:
Code Block |
---|
} par_str = line[pos_eq+1:].strip(' ').rstrip('\n') {code} h1. Python - useful references h3. |
Python - useful references
Built-in
...
functions
...
http://docs.python.org/library/functions.html
...
setattr - gives dynamic variables in python
http://docs.python.org/library/functions.html#setattr
...
PyQt4
How to open/close
...
/move other
...
GUI
...
window?
...
Try
...
to
...
close
...
window
...
if
...
its
...
object
...
exists,
...
othervise
...
-
...
open:
Code Block |
---|
{close} def processConfigPars(self): print 'processConfigPars' try : cp.confpars.guiconfigparameters.close() except : # AttributeError: #NameError cp.confpars.guiconfigparameters = guiconfigpars.GUIConfigParameters() cp.confpars.guiconfigparameters.setParent(self)move(self.pos().__add__(QtCore.QPoint(100,330))) # window offset # or use self.parentWidget().pos() for combined widgets: # cp.confpars.guiconfigparametersguifilebrowser.move(self.parentWidget().pos().__add__(QtCore.QPoint(100240,33040))) # window offset cp.confpars.guiconfigparameters.show() |
Note |
---|
Sometime it looks like the window does not want to move in specified position... |
How to close window and delete object?
Code Block |
---|
{close} h3. How to close window and delete object? {close} def closeEvent(self, event): try: # try to delete self object in the cp.confpars del cp.confpars.guiconfigparameters except # AttributeError: pass # silently ignore {close} h1. Matplotlib In examples below we assume {code} |
Matplotlib
In examples below we assume
Code Block |
---|
axes = fig.add_subplot(111) axim = axes.imshow(arrwin, interpolation='nearest', origin='bottom', aspect='auto') |
How to define empty axes with limits
Code Block |
---|
{code}
h3. How to define empty axes with limits
{code}
fig = plt.figure(figsize=(10,10), dpi=100, facecolor='w',edgecolor='w',frameon=True)
axes = fig.add_subplot(111)
axes.set_xlim((-50,1750))
axes.set_ylim((-50,1750))
|
How to draw line
Code Block |
---|
{code} h3. How to draw line {code} import matplotlib.lines as lines line = lines.Line2D(arrx, arry, linewidth=1, color='r') axes.add_artist(line) {code} h3. How to draw axis without labels {code |
How to draw axis without labels
Code Block |
---|
}
import matplotlib.ticker as mtick
axes.xaxis.set_major_formatter( mtick.NullFormatter() )
|
How to rotate axis labels
Code Block |
---|
{code} h3. How to rotate axis labels {code} for label in axes.get_xticklabels() : label.set_rotation(60) # rotate by 60 degree label.set_horizontalalignment('center') # 'right', etc. {code} h3. How to change axis label position on the plot {code} |
How to change axis label position on the plot
Code Block |
---|
axes.xaxis.set_ticks_position('top')
axes.yaxis.set_ticks_position('right')
{code}
h3. How to make figure with |
How to make figure with non-equal
...
subplots
Code Block |
---|
} import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(20, 20) # Naive direction [ Y , X ] axsa = fig.add_subplot(gs[ 1:16, 0:14]) axsb = fig.add_subplot(gs[ 1:16, 14:19]) axsc = fig.add_subplot(gs[16: , 0:14]) {code} h3. How to draw a color bar as a separate sub-plot {code} |
How to draw a color bar as a separate sub-plot
Code Block |
---|
axCB = fig.add_subplot(gs[ 0, 0:14])
colb = fig.colorbar(axim, cax=axCB, orientation='horizontal')
axCB.xaxis.set_ticks_position('top') # change position of axis labels
{code}
h3. How draw text
{code} |
How draw text
Code Block |
---|
plt.text(x, y, text, fontsize=7, color='k', ha='left', rotation=45) |
At the edge of matplotlib and PyQt4
We assume that everything is done in our backend basis:
Code Block |
---|
{code} h1. At the edge of matplotlib and PyQt4 We assume that everything is done in our backend basis: {code} import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt {code} h3. How to get the current matplotlib figure window position on monitor {code} |
How to get the current matplotlib figure window position on monitor
Code Block |
---|
pos = fig.canvas.manager.window.pos()
print 'x,y=', pos.x(), pos.y()
{code}
h3. How to move the matplotlib figure window in certain |
How to move the matplotlib figure window in certain (x,y)
...
position
Code Block |
---|
} fig.canvas.manager.window.move(x,y) # in pixels from top-left corner {code} h3. How to move the |
How to move the matplotlib figure window on top (of all pileup windows)
Code Block |
---|
matplotlib figure window on top (of all pileup windows) {code} fig.canvas.manager.window.activateWindow() # Makes window active fig.canvas.manager.window.raise_() # Moves window on top {code} |
the
...
attribute
...
trick
...
is
...
that
...
the
...
fig.canvas.manager.window
...
returns
...
the
...
QtGui.QMainWindow
...
,
...
which
...
is
...
subclass
...
of
...
QtGui.QWidget
...
with
...
all
...
that
...
useful
...
methods.
How to add figure as a widget of the QtGui
Code Block |
---|
h3. How to add figure as a widget of the QtGui {code} fig = plt.figure(num=None figsize=(5,10), dpi=100, facecolor='w',edgecolor='w',frameon=True) vbox = QtGui.QVBoxLayout() vbox.addWidget(fig.canvas) # Wraps figure canvas in widget self.setLayout(vbox) {code} h3. How to receive a signal |
How to receive a signal in program when window is activated by the mouse click on frame ?
I do not know yet...
But, if you click on figure canvas (the region inside the window frame, use
Code Block |
---|
in program when window is activated by the mouse click on frame ?
I do not know yet...
But, if you click on figure canvas (the region inside the window frame, use
{code}
fig.canvas.mpl_connect('button_press_event', self.onButtonPressEvent)
#Should be implemented something like:
def onButtonPressEvent( self, event ):
"""Figure is picked"""
print 'click on fig number =', event.canvas.figure.number
|
How to receive a signal in program when close window by the click on "X"
Code Block |
---|
{code}
h3. How to receive a signal in program when close window by the click on "X"
{code}
fig.canvas.mpl_connect('close_event', self.onCloseEvent)
#Should be implemented something like:
def onCloseEvent( self, event ):
print 'close event, fig number =', event.canvas.figure.number
|
How to close figure from program call
Code Block |
---|
{code} h3. How to close figure from program call {code} plt.close( num ) # close figure with known number num ... plt.close('all') # close all figures {code} |