473,499 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Printing Varable Names Tool.. Feedback requested.


Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)

Anyway, here's the source with an example output. I'm still not sure
what to call it. Pnames stands for printnames, but if you think of
something better let me know.

Some things I think will be good is shortening long output such as
lists and dictionaries to '[...]' or '[:] or a few chars at the
beginning and end with '...' in the middle. I think it's important to
keep the output short and readable.

Any suggestions would be apreciated. :)

Ron
IDLE 1.1.1c1 ==== No Subprocess ====
[globals]
__builtins__ --> <module>
__doc__ --> <docstring>
__file__ --> C:\Python24\Lib\idlelib\idle.pyw
__main__ --> <module>
__name__ --> __main__
g --> 45
glist --> ['a changed', 'list'] <-- test2:a
h --> 45
idlelib --> <module>
pnames --> <function>
sys --> <module>
test1 --> <function>
test2 --> <function>
test2.at1 --> [True] <-- test2:aaa
[test1]
t --> ['altered'] <-- test2:w
[locals:test2]
a --> ['a changed', 'list'] <-- globals:glist
aaa --> [True] <-- globals:test2.at1
w --> ['altered'] <-- test1:t
Paused


#---start---

# pnames.py
"""
A utility to print the value of variables for
debugging purposes.

To use: import prnames and insert prnames.prnames()
in the program where you want to examin names.
Pressing any key will continue.

Author: Ronald Adam
"""

import sys
if __name__ is not '__main__':
import __main__

def pnames():
"""
View
"""
objdict = {} # Collect references to object.
namelist = [] # List of names and values by frame.
n = 1
name = None
while name!= 'runcode':
# Move up in the frames to gather name data.
# until the application global frame is reached.
name = sys._getframe(n).f_code.co_name
if name != 'runcode': # This keeps it out of idle's name
space.
namelst = [name,[]]
namespace = sys._getframe(n).f_locals
keys = namespace.keys()
# Get all the names in this frame.
for k in keys:
try:
trash = objdict[id(namespace[k])][name]
except:
try:
objdict[id(namespace[k])][name]=[k]
except:
objdict[id(namespace[k])]={name:[k]}
else:
objdict[id(namespace[k])][name].append(k)
namelst[1].append((k,namespace[k],id(namespace[k])))
#namelist.append(namelst)
#try:
attribs = None
try:
attribs = namespace[k].func_dict
except:
pass
if attribs:
for att in attribs:
attname = k+'.'+att
try:
trash = objdict[id(attribs[att])][attname]
except:
try:

objdict[id(attribs[att])][name]=[attname]
except:

objdict[id(attribs[att])]={name:[attname]}
else:

objdict[id(attribs[att])][name].append(attname)

namelst[1].append((attname,attribs[att],id(attribs[att])))
namelist.append(namelst)

n += 1
# Now print what we collected.
namelist.reverse() # Reverse it so we have globals at the
top.
tab = 0
for gname, group in namelist:
# Sort it.
def sortnocase(stringlist):
tupleList = [(x[0].lower(), x) for x in stringlist]
tupleList.sort()
return [x[1] for x in tupleList]
group = sortnocase(group)
if gname == chr(63): # Idle uses this as name as
app-globals.
gname = 'globals'
if gname == namelist[-1:][0][0]:
gname = 'locals:'+gname # Indicate locals group.
print '%s[%s]'%(' '*tab, gname)
tab += 1

for name, obj, objid in group:
# Print the varable name
print ' '*tab,name,'-->',

# Remove & replace a lot of clutter as we print it.
# List other names pointing to mutable objects.
if name == '__doc__':
obj = '<docstring>'
if 'module' in str(obj): # These remove clutter
obj = '<module>' # More probably needs to be
if 'function' in str(obj): # done here.
obj = '<function>'

# Print the object
print obj,

# Print the other names pointing to
# the object.
obj2 = ''
if type(obj) not in [int, str, float, bool, tuple] \
and obj not in [True, False, None]:
for obj in objdict[objid].keys():
name2 = objdict[objid][obj]
n = 0
if len(name2):
for name3 in name2:
if obj == chr(63):
obj = 'globals'
if name3 != name:
if n>0:
obj2 += ', '
if obj != gname:
obj2 += obj+':'+name3
else:
obj2 += name3
n += 1

if len(obj2)>0:
obj2 = '<-- '+obj2
print obj2
raw_input( 'Paused')

def test1():
global g
t = g
t = [9]
test2.at1 = [True]
test2(t)

def test2(w):
a = glist
aaa = test2.at1
test2.at1[0] = True
a[0] = 'a changed'
w[0] = 'altered'
pnames()
if __name__ == '__main__':
# Make a few globals to see.
g = 45
h = g
glist = ['just a','list']

# Put an attribute on a function
# to find.
test2.at1 = 25

# Run test function.
test1()

#---end---
Jul 18 '05 #1
3 1807
On Thu, 31 Mar 2005 18:37:53 GMT, Ron_Adam <ra****@tampabay.rr.com>
wrote:

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)

Here's the error I'm getting from the python command window.

C:\ron\rondev\pythonmods>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
import pnames
pnames.pnames() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "pnames.py", line 28, in pnames
name = sys._getframe(n).f_code.co_name
ValueError: call stack is not deep enough


Jul 18 '05 #2


Fixed it so it now runs from the command line and from winpython as
well as idle in Python 2.4 on Windows Xp. I still don't know about
linux systems.

I decided on viewnames.py as the filename and viewit() as the calling
name.

#---start---

# viewnames.py
"""
A utility to print the value of variables for
debugging and instructional purposes.

To use:
from viewnames import viewit
viewit()

Insert it in the program where you want to examine names.
It will pause after it prints so that it will work in loops.

Author: Ronald Adam
"""

import sys
if __name__ is not '__main__':
import __main__

def readnames():
"""
Build a sequential name list and a dictionary of
objects and name references by groups.
"""
objdict = {} # Collect references to object.
namelist = [] # List of names and values by frame.
n = 2
name = None
while name not in ['runcode', 'RunScript', chr(63)]:
# Move up in the frames to gather name data.
# until the application global frame is reached.
name = sys._getframe(n).f_code.co_name
#print name
namelst = [name,[]]
namespace = sys._getframe(n).f_locals
keys = namespace.keys()
# Get all the names in this frame.
for k in keys:
try:
trash = objdict[id(namespace[k])][name]
except:
try:
objdict[id(namespace[k])][name]=[k]
except:
objdict[id(namespace[k])]={name:[k]}
else:
objdict[id(namespace[k])][name].append(k)
namelst[1].append((k,namespace[k],id(namespace[k])))
# Read any attributes if there is a dictionary.
attribs = None
try:
attribs = namespace[k].func_dict
except:
pass
if attribs:
for att in attribs:
attname = k+'.'+att
try:
trash = objdict[id(attribs[att])][attname]
except:
try:
objdict[id(attribs[att])][name]=[attname]
except:
objdict[id(attribs[att])]={name:[attname]}
else:

objdict[id(attribs[att])][name].append(attname)

namelst[1].append((attname,attribs[att],id(attribs[att])))
namelist.append(namelst)
n += 1
return objdict, namelist

def sortnocase(stringlist):
tupleList = [(x[0].lower(), x) for x in stringlist]
tupleList.sort()
return [x[1] for x in tupleList]

def printnames( objdict, namelist):
"""
Now print what we collected.
"""
namelist.reverse() # Reverse it so we have globals at the
top.
tab = 0
for gname, group in namelist:
# Print group name.
if gname == chr(63): # Idle uses this as name as
app-globals.
gname = 'globals'
if gname == namelist[-1:][0][0]:
gname = 'locals:'+gname # Indicate locals group.
print '%s[%s]'%(' '*tab, gname)
tab += 1

# Print group items.
# Sort group fist.
group = sortnocase(group)
for name, obj, objid in group:

# Print the varable name
print ' '*tab,name,'-->',

# Print object
# Remove & replace a lot of clutter as we print it.
# List other names pointing to mutable objects.
obj2 = obj # Make a copy to edit if needed.
if name == '__doc__':
if len(str(obj))>30:
obj2 = obj2.strip()
obj2 = '"'+obj2[:6]+' ... '+obj2[-6:]+'"'
#obj = '<docstring>'
if 'module' in str(obj): # These remove clutter
obj2 = '<module>' # More probably needs to be
if 'function' in str(obj): # done here.
obj2 = '<function>'

# Print the object
print obj2,

# Print the other names pointing to
# the object.
endofline = ''
# If object is immutable, don't print references.
if type(obj) not in [int, str, float, bool, tuple] \
and obj not in [True, False, None]:
for key in objdict[objid].keys():
grp = key
if key == chr(63):
grp = 'globals'

namegroup = objdict[objid][key]
n = 0
for nm in namegroup:
if nm != name:
if n>0:
endofline += ', '
if grp != gname:
endofline += grp+':'+nm
else:
endofline += nm
n += 1

if len(endofline)>0:
endofline = '<-- '+endofline
print endofline

def viewit():
""" Show current names """
objdict, namelist = readnames()
print
printnames( objdict, namelist)
print
raw_input('Press enter to continue.')
"""
A few nonsense test functions.
"""
def test1():
global g
t = g
t = [9]
test2.at1 = [True]
test2(t)

def test2(w):
a = glist
aaa = test2.at1
test2.at1[0] = True
a[0] = 'a changed'
w[0] = 'altered'
viewit()
if __name__ == '__main__':
# Make a few globals to see.
g = 45
h = g
glist = ['just a','list']

# Put an attribute on a function
# to find.
test2.at1 = 25

# Run test function.
test1()

#---end---
Jul 18 '05 #3
On Thu, 31 Mar 2005 19:13:39 GMT, Ron_Adam <ra****@tampabay.rr.com>
wrote:
On Thu, 31 Mar 2005 18:37:53 GMT, Ron_Adam <ra****@tampabay.rr.com>
wrote:

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)

Here's the error I'm getting from the python command window.

C:\ron\rondev\pythonmods>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
import pnames
pnames.pnames()Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "pnames.py", line 28, in pnames
name = sys._getframe(n).f_code.co_name
ValueError: call stack is not deep enough

I fixed it, it now works in winpython and from the command line.

If anyones interested.

Ron

Jul 18 '05 #4

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

Similar topics

1
1710
by: James | last post by:
how come when i print programicly my printer says "data received" and it won't print until i press the GO button on the printer? my printer is a HP laser jet 5 Set objFS =...
2
5190
by: Mindful_Spirit | last post by:
I'm trying to set up a basic email feed back form like this, and was wondering about some basic configuration settings. I have used code from this website. I have it working just fine. I'm...
3
2176
by: Chrisitiaan | last post by:
Hi, I want to develop a 'truly' object oriented application, that is, my business logic objects handle the business logic (of course) and the persistence to a MS SQL server database. The user...
1
2564
by: Pohihihi | last post by:
Hello NG. I am using System.Drawing.Printing NS to print few label style printouts. I figured out how the basics goes in that namespace but there are still few things that is holding me up from...
1
2039
by: Gary | last post by:
Open the web browser at the same time, the session varable in the second broswer is disappeared. All The Session Varable is declared in the webform page load.
2
1601
by: Suresh Kumar Rathod | last post by:
HI friends... Can any body give reason / logic behind static varable lifetime through out the process execution. i.e how does compiler maintains the static varable life through out the process...
2
1487
by: pedestrian via SQLMonster.com | last post by:
I wonder is there any way I can turn off the "Documentation Feedback" section of the Books Online at the bottom of the pages... I'm printing some Books Online pages for own reference. Thanks in...
6
4544
by: =?Utf-8?B?QnJhc3NpY2FOaWdyYQ==?= | last post by:
Greetings, I have a web application that prints a form using PrintDocument on the server. Currently it is set up to print to the default printer (on the server). My users would like to be...
18
11263
by: Brett | last post by:
I have an ASP.NET page that displays work orders in a GridView. In that GridView is a checkbox column. When the user clicks a "Print" button, I create a report, using the .NET Framework printing...
0
7007
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
7386
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5468
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4918
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4599
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3098
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3090
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
664
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
295
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.