473,387 Members | 1,379 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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

Hello,

I need to access the code inside of a context manager, i.e. the call to

with myManager(v=5) as x:
a=b
c=sin(x)
should cause the following output (minus the first line, if that's easier):
with myManager(v=5) as x: # I could live without this line
a=b
c=sin(x)
I can get the line number from the traceback (see below), and try to
find the block in the source, but that seems ugly to me.

class MyManager(object):
def __init__(self,name='name'):
# how to access the source code inside of the with block ?
f = traceback.extract_stack()
print f[0]

def __enter__(self):
pass

def __exit__(self,type,value,traceback):
if type is not None:
print 'exception'
pass

Any ideas?

Daniel
Nov 18 '08 #1
4 1684
On Nov 18, 3:59*pm, Daniel <inva...@invalid.invalidwrote:
Hello,

I need to access the code inside of a context manager, i.e. the call to

with myManager(v=5) as x:
* * * * a=b
* * * * c=sin(x)

should cause the following output (minus the first line, if that's easier):

with myManager(v=5) as x: # I could live without this line
* * * * a=b
* * * * c=sin(x)

I can get the line number from the traceback (see below), and try to
find the block in the source, but that seems ugly to me.

class MyManager(object):
* * def __init__(self,name='name'):
* * * * # how to access the source code inside of the with block ?
* * * * f = traceback.extract_stack()
* * * * print f[0]

* * def __enter__(self):
* * * * pass

* * def __exit__(self,type,value,traceback):
* * * * if type is not None:
* * * * * * print 'exception'
* * * * pass

Any ideas?

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.
Nov 19 '08 #2
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.
Nov 19 '08 #3
See below.

On Nov 19, 8:02*am, Daniel <inva...@invalid.invalidwrote:
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.

Hi. It is not the role of a 'dataStore' object in your object model,
which is why, ideally, you would separate those two functions.
However, if 'dataStore' always needs the printing functionality, you
could built it in for practical reasons. That has the benefit that
you don't need to specify, such as 'print_next_lines( 5 )', how many
lines to print, since the context manager can count for you, and if
you add a line, you won't need to change to 'print_next_lines( 6 )'.
Lastly, you could use two con. managers, such as:

with printing:
with dataStore('measurement1.dat') as d:
magnet.setField(0)

You may or may not find that relevant.

Here is some code and output:

import inspect
class CM( object ):
def __enter__(self):
self.startline= inspect.stack( )[ 1 ][ 0 ].f_lineno
def __exit__(self, exc_type, exc_value, traceback):
endline= inspect.stack( )[ 1 ][ 0 ].f_lineno
print self.startline, endline

with CM(): #line 9
a= 0
b= 1
c= 2

with CM(): #line 14
d= 3
e= 4

/Output:

9 12
14 16
Nov 20 '08 #4
Hi Aaron,

the dataStore combines both the printing and analysis (it will create a
report).
Unfortunately the end of the block already needs to be known in
__enter__, as the report starts to print during the measurement.
I decided to do it the following way:

__enter__ gets the start line number using the idea you proposed.
then the program reads the number of lines that are indented with
respect to the with block. This could cause problems for strange
indenting, but this should not happen in my application. Unfortunately I
could not use the ast module, because the comments are an important part
of the report.

Thank you for your ideas

Daniel


class CM( object ):
def __enter__(self):
self.startline= inspect.stack( )[ 1 ][ 0 ].f_lineno
print 'startline',self.startline
filename = inspect.stack( )[-1][1]

def getIndentation(line):
# TODO: handle comments and docstrings correctly
return len(line) - len(line.lstrip())

with open(filename,'r') as f:
lines=f.readlines()[self.startline-1:]
indent0=getIndentation(lines[0])
indent =[getIndentation(i)-indent0 for i in lines[1:]]
nlines = [n for l,n in zip(indent,xrange(1,1000000)) if l >
0][0]
self.callingCode = lines[:self.startline+nlines]

print self.callingCode
def __exit__(self, exc_type, exc_value, traceback):
pass

if __name__ == '__main__':
with CM():
print 'in first'
a= 0
b= 1
c= 2
print 'end of first'

with CM():
d= 3
e= 4
Nov 20 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: SPG | last post by:
Hi, I am relatively new to TOMCAT, and am trying to deploy a web app using it. I have a domain name that I want to use to access my web app directly. By default, I deploy my WAR, and it deploys...
6
by: Páll Ólafsson | last post by:
Hi I have a problem with the Microsoft.ApplicationBlocks.ExceptionManagement? I can't get it to work in RELEASE mode? If I run the project in debug mode the block works fine but when I run the...
20
by: ishmael4 | last post by:
hello everyone! i have a problem with reading from binary file. i was googling and searching, but i just cant understand, why isnt this code working. i could use any help. here's the source code:...
5
by: PCC | last post by:
I am using the Exception Managment Application Block on Windows Server 2003 Enterprise and .NET v1.1. If I use the block with an ASP.NET web wervice or in a web application I get the following...
32
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open...
3
by: kent | last post by:
Hi, For the code below, only "aaa" has a red background but "bbb" and "ccc" don't have it: <div style="background: red">aaa <div style="float:left">bbb</div> <div...
7
by: =?Utf-8?B?YWxiZXJ0b3Nvcmlh?= | last post by:
Hi everybody, I'm using a system.timers.timer object like this: Dim aTimer As New System.Timers.Timer() In my page_load event I use this: aTimer.Interval = 5000 aTimer.Enabled = True...
0
by: =?Utf-8?B?UG9sbHkgQW5uYQ==?= | last post by:
Hi, I have previously used EL v 3.1 Exception Handling application block successfully. I thought I would now try to do the same with EL v 4.0. My first experiment was to replace an exception....
3
by: John Devlon | last post by:
Hi, I would like to use the ASP.NET configuration manager to configure users and roles. But when clicking on the securitt tab, the screen go's blanc. I'm using an Acces data provider, which...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.