PDA

View Full Version : python - list variables in imported script?


EightBit
07-24-2012, 04:56 PM
If I have:
import myProjScript as mp
and
myProjScript.py has these vars:
fruit = ['apple', 'orange']
color = ['red','blue']

Is there a way to list the vars/values in myProjScript from inside the script editor?
Thanks.

Kriz
07-24-2012, 05:37 PM
Is something like this what you are looking for?


import myProjScript as mp

for variable in dir(mp):
print 'Variable:', variable
print 'Type:', type(variable)
print 'Value:', eval('%s.%s' % ('mp', variable))
print

NaughtyNathan
07-24-2012, 08:06 PM
you can also just assign "global" variables in your script and these become attributes of the script object... you can even set them.
# this is myPythonScript.py
fruit = ['apple', 'orange']
color = ['red','blue']

def showFruit():
print 'the current fruit list is:', fruit

def blahblah():
# etc...
pass

If you had a script file like the above, you could then do:
import myPythonScript
myPythonScript.showFruit()
the current fruit list is: ['apple', 'orange']

myPythonScript.fruit
# Result: ['apple', 'orange'] #

myPythonScript.fruit.append('banana')
myPythonScript.showFruit()
the current fruit list is: ['apple', 'orange', 'banana']

myPythonScript.fruit = [ 'loganberry', 'raspberry' ]
myPythonScript.fruit
# Result: [ 'loganberry', 'raspberry' ] #

myPythonScript.color = [ 'yellow', 'green' ]
myPythonScript.color
# Result: ['yellow', 'green'] #

and so on...

EightBit
07-26-2012, 03:00 PM
Thanks for these replies.

What I'd like to do is only show the vars that are strings and lists (ie, not the functions and not the built-in vars).
So in my out put, I don't want this stuff:

Variable: __doc__
Value: None
Variable: __file__
Value: C:\Users\Mitch\Documents\maya\pixlScripts\SloanSetup.pyc
Variable: __name__
Value: SloanSetup
Variable: __package__
Value: None
Variable: showObjs
Value: <function showObjs at 0x000000003EDBD0B8>

Is it easy to filter them out using Kriz' approach?
Else I would create the 'show' function per Nathan and simply add all my vars to it.
Thanks again.

Kriz
07-26-2012, 03:05 PM
import myProjScript as mp

for variable in dir(mp):
if not variable.startswith('__'):
print 'Variable:', variable
print 'Type:', type(variable)
print 'Value:', eval('%s.%s' % ('mp', variable))
print

EightBit
07-26-2012, 07:37 PM
Thanks a lot, that helped me get exactly what I wanted:
for variable in dir(sloan):
varStr = str(eval('%s.%s' % ('sloan', variable)) )
if not ( variable.startswith('__') or 'function' in varStr or variable == 'cmds' ):
print 'Variable:', variable
# print 'Type:', type(variable)
print 'Value:', varStr

CGTalk Moderation
07-26-2012, 07:37 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.