how to acces the block inside of a context manager as sourcecode

Daniel invalid at invalid.invalid
Wed Nov 19 09:02:47 EST 2008


Hi Aaron,

let me give you the reason for the context manager:
I am driving handware with a python script, basically a data acquisition
program which looks like this:


with dataStore('measurement1.dat') as d:
	magnet.setField(0)
	r1=doExperiment(voltage=0.345, current=0.346, temperature=33)
	magnet.setField(1)
	r2=doExperiment(voltage=0.32423, current=0.3654, temperature=45)
	d.append(r2-r1)

the script does the measuring and the context manager stores the result
(r1 and r2), at the end the result is printed.

The source code serves as the documentation (it contains many parameters
that need to be well documented), so I print the source code, cut it out
and glue it into my lab notebook.
Now I want to automate this process, i.e. the dataStore should print the
sourcecode.

Daniel

> There isn't a solution in the general case, because strings can be
> executed.  However, 'inspect.currentframe()' and
> 'inspect.getsourcelines(object)' can handle some cases, and your idea
> is (I believe) how getsourcelines works itself.  You can probably do
> it without a context manager, e.g. 'print_next_lines( 5 )' or
> 'print_prior_lines( 2 )', dedenting as needed.



More information about the Python-list mailing list